Authored by chunhua.zhang

add new role: switch

yoho.switch
=========
有货故障切换脚本
切换流程
------------
### 公网域名解析
#### `有货前台`: `api.yoho.cn` , `service.yoho.cn`, `union.yoho.cn`, `webunion.yohobuy.com`
- default: `123.206.1.98`
- backup 1: `123.206.2.50`
- backup 2(灰度): `140.143.181.49`
#### `pch5`: `*.yohobuy.com`, `*.m.yohobuy.com`
- default: 140.143.217.201
> 云负载均衡器是跨多AZ可用的, 所以一般不需要切换域名
>
> 需要切换域名的场景: 某个负载均衡器出现故障
>
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
License
-------
BSD
Author Information
------------------
chunhua.zhang@yoho.cn
\ No newline at end of file
... ...
---
# defaults file for yoho.switch
\ No newline at end of file
... ...
---
# handlers file for yoho.switch
\ No newline at end of file
... ...
galaxy_info:
author: your name
description: your description
company: your company (optional)
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: http://example.com/issue/tracker
# Some suggested licenses:
# - BSD (default)
# - MIT
# - GPLv2
# - GPLv3
# - Apache
# - CC-BY
license: license (GPLv2, CC-BY, etc)
min_ansible_version: 1.2
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
# Optionally specify the branch Galaxy will use when accessing the GitHub
# repo for this role. During role install, if no tags are available,
# Galaxy will use this branch. During import Galaxy will access files on
# this branch. If Travis integration is configured, only notifications for this
# branch will be accepted. Otherwise, in all cases, the repo's default branch
# (usually master) will be used.
#github_branch:
#
# platforms is a list of platforms, and each platform has a name and a list of versions.
#
# platforms:
# - name: Fedora
# versions:
# - all
# - 25
# - name: SomePlatform
# versions:
# - all
# - 1.0
# - 7
# - 99.99
galaxy_tags: []
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags. Be sure to
# remove the '[]' above, if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
dependencies: []
# List your role dependencies here, one per line. Be sure to remove the '[]' above,
# if you add dependencies to this list.
\ No newline at end of file
... ...
---
# tasks file for yoho.switch
\ No newline at end of file
... ...
---
- hosts: localhost
remote_user: root
roles:
- yoho.switch
\ No newline at end of file
... ...
---
# vars file for yoho.switch
\ No newline at end of file
... ...
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author chunhua.zhang@yoho.cn
import random
import hmac
import base64
import hashlib
import time
import requests
class QcloudApi:
"""腾讯云API接口"""
'pre-defined url'
'load balance'
URLS_lb = 'lb.api.qcloud.com/v2/index.php'
URLS_DNS = 'cns.api.qcloud.com/v2/index.php'
'public request params'
Region = 'ap-beijing'
Version = 'YOHO-QCLOUD-V1.0'
'see doc: https://www.qcloud.com/document/api/377/4153'
'init. must provide SecretId and SecretKey'
def __init__(self, secretId, secretKey):
self.secretId = secretId
self.secretKey = secretKey
def do_query(self, params, req_url=URLS_lb):
"""
Do Query Qcloud api
:param params: 查询参数,dict类型,必须包含 Action
:param req_url: 查询的地址,参考:qcloud_api.URLS_lb --> lb.api.qcloud.com/v2/index.php
:return: dict类型,腾讯云返回的消息体
"""
if 'Action' not in params:
print("must provide [Action] params !")
raise ValueError(params)
public_params = {'RequestClient': QcloudApi.Version, 'limit': 100, 'Region': QcloudApi.Region, 'Timestamp': int(time.time()), 'Nonce': QcloudApi.generate_nonce(), 'SecretId': self.secretId}
# merge params
params = dict(params, **public_params)
# signature
sign = self.signature(params, req_url)
params['Signature'] = sign
response_dict = requests.post("https://" + req_url, data=params).json()
print("Query qcloud api success. params: %s, result: %s" % (params, response_dict))
return response_dict
@staticmethod
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def signature(self, request_params, url):
"""
对消息进行签名 see https://www.qcloud.com/document/api/377/4214
@param request_params
@param url, 请求地址,例如:lb.api.qcloud.com/v2/index.php
"""
# sort dict by key
kv_pairs = []
for key in sorted(request_params):
kv_pairs.append('%s=%s' % (key, request_params[key]))
str_req = '&'.join(kv_pairs)
str_full = 'POST%s?%s' % (url, str_req)
hmac_sign = hmac.new(bytes(self.secretKey), bytes(str_full), hashlib.sha1).digest()
return base64.b64encode(hmac_sign).decode()
# for test
if __name__ == "__main__":
api = QcloudApi(secretId='AK**K', secretKey='AC**QaW')
api.do_query(params={'Action': 'DescribeLoadBalancers'}, req_url=QcloudApi.URLS_lb)
... ...