Authored by chunhua.zhang

add new role: switch

  1 +yoho.switch
  2 +=========
  3 +
  4 +有货故障切换脚本
  5 +
  6 +切换流程
  7 +------------
  8 +
  9 +
  10 +### 公网域名解析
  11 +
  12 +#### `有货前台`: `api.yoho.cn` , `service.yoho.cn`, `union.yoho.cn`, `webunion.yohobuy.com`
  13 + - default: `123.206.1.98`
  14 + - backup 1: `123.206.2.50`
  15 + - backup 2(灰度): `140.143.181.49`
  16 +
  17 +
  18 +#### `pch5`: `*.yohobuy.com`, `*.m.yohobuy.com`
  19 + - default: 140.143.217.201
  20 +
  21 +> 云负载均衡器是跨多AZ可用的, 所以一般不需要切换域名
  22 +>
  23 +> 需要切换域名的场景: 某个负载均衡器出现故障
  24 +>
  25 +
  26 +
  27 +
  28 +Role Variables
  29 +--------------
  30 +
  31 +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.
  32 +
  33 +Dependencies
  34 +------------
  35 +
  36 +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.
  37 +
  38 +Playbook
  39 +----------------
  40 +
  41 +Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
  42 +
  43 + - hosts: servers
  44 + roles:
  45 + - { role: username.rolename, x: 42 }
  46 +
  47 +License
  48 +-------
  49 +
  50 +BSD
  51 +
  52 +Author Information
  53 +------------------
  54 +
  55 +chunhua.zhang@yoho.cn
  1 +---
  2 +# defaults file for yoho.switch
  1 +---
  2 +# handlers file for yoho.switch
  1 +galaxy_info:
  2 + author: your name
  3 + description: your description
  4 + company: your company (optional)
  5 +
  6 + # If the issue tracker for your role is not on github, uncomment the
  7 + # next line and provide a value
  8 + # issue_tracker_url: http://example.com/issue/tracker
  9 +
  10 + # Some suggested licenses:
  11 + # - BSD (default)
  12 + # - MIT
  13 + # - GPLv2
  14 + # - GPLv3
  15 + # - Apache
  16 + # - CC-BY
  17 + license: license (GPLv2, CC-BY, etc)
  18 +
  19 + min_ansible_version: 1.2
  20 +
  21 + # If this a Container Enabled role, provide the minimum Ansible Container version.
  22 + # min_ansible_container_version:
  23 +
  24 + # Optionally specify the branch Galaxy will use when accessing the GitHub
  25 + # repo for this role. During role install, if no tags are available,
  26 + # Galaxy will use this branch. During import Galaxy will access files on
  27 + # this branch. If Travis integration is configured, only notifications for this
  28 + # branch will be accepted. Otherwise, in all cases, the repo's default branch
  29 + # (usually master) will be used.
  30 + #github_branch:
  31 +
  32 + #
  33 + # platforms is a list of platforms, and each platform has a name and a list of versions.
  34 + #
  35 + # platforms:
  36 + # - name: Fedora
  37 + # versions:
  38 + # - all
  39 + # - 25
  40 + # - name: SomePlatform
  41 + # versions:
  42 + # - all
  43 + # - 1.0
  44 + # - 7
  45 + # - 99.99
  46 +
  47 + galaxy_tags: []
  48 + # List tags for your role here, one per line. A tag is a keyword that describes
  49 + # and categorizes the role. Users find roles by searching for tags. Be sure to
  50 + # remove the '[]' above, if you add tags to this list.
  51 + #
  52 + # NOTE: A tag is limited to a single word comprised of alphanumeric characters.
  53 + # Maximum 20 tags per role.
  54 +
  55 +dependencies: []
  56 + # List your role dependencies here, one per line. Be sure to remove the '[]' above,
  57 + # if you add dependencies to this list.
  1 +---
  2 +# tasks file for yoho.switch
  1 +---
  2 +- hosts: localhost
  3 + remote_user: root
  4 + roles:
  5 + - yoho.switch
  1 +---
  2 +# vars file for yoho.switch
  1 +#!/usr/bin/python
  2 +# -*- coding: UTF-8 -*-
  3 +# author chunhua.zhang@yoho.cn
  4 +import random
  5 +import hmac
  6 +import base64
  7 +import hashlib
  8 +import time
  9 +import requests
  10 +
  11 +
  12 +class QcloudApi:
  13 + """腾讯云API接口"""
  14 +
  15 + 'pre-defined url'
  16 + 'load balance'
  17 + URLS_lb = 'lb.api.qcloud.com/v2/index.php'
  18 + URLS_DNS = 'cns.api.qcloud.com/v2/index.php'
  19 +
  20 + 'public request params'
  21 + Region = 'ap-beijing'
  22 + Version = 'YOHO-QCLOUD-V1.0'
  23 +
  24 + 'see doc: https://www.qcloud.com/document/api/377/4153'
  25 + 'init. must provide SecretId and SecretKey'
  26 + def __init__(self, secretId, secretKey):
  27 + self.secretId = secretId
  28 + self.secretKey = secretKey
  29 +
  30 + def do_query(self, params, req_url=URLS_lb):
  31 + """
  32 + Do Query Qcloud api
  33 + :param params: 查询参数,dict类型,必须包含 Action
  34 + :param req_url: 查询的地址,参考:qcloud_api.URLS_lb --> lb.api.qcloud.com/v2/index.php
  35 + :return: dict类型,腾讯云返回的消息体
  36 + """
  37 + if 'Action' not in params:
  38 + print("must provide [Action] params !")
  39 + raise ValueError(params)
  40 +
  41 + public_params = {'RequestClient': QcloudApi.Version, 'limit': 100, 'Region': QcloudApi.Region, 'Timestamp': int(time.time()), 'Nonce': QcloudApi.generate_nonce(), 'SecretId': self.secretId}
  42 + # merge params
  43 + params = dict(params, **public_params)
  44 + # signature
  45 + sign = self.signature(params, req_url)
  46 + params['Signature'] = sign
  47 + response_dict = requests.post("https://" + req_url, data=params).json()
  48 + print("Query qcloud api success. params: %s, result: %s" % (params, response_dict))
  49 + return response_dict
  50 +
  51 + @staticmethod
  52 + def generate_nonce(length=8):
  53 + """Generate pseudorandom number."""
  54 + return ''.join([str(random.randint(0, 9)) for i in range(length)])
  55 +
  56 + def signature(self, request_params, url):
  57 + """
  58 + 对消息进行签名 see https://www.qcloud.com/document/api/377/4214
  59 + @param request_params
  60 + @param url, 请求地址,例如:lb.api.qcloud.com/v2/index.php
  61 + """
  62 + # sort dict by key
  63 + kv_pairs = []
  64 + for key in sorted(request_params):
  65 + kv_pairs.append('%s=%s' % (key, request_params[key]))
  66 + str_req = '&'.join(kv_pairs)
  67 + str_full = 'POST%s?%s' % (url, str_req)
  68 + hmac_sign = hmac.new(bytes(self.secretKey), bytes(str_full), hashlib.sha1).digest()
  69 + return base64.b64encode(hmac_sign).decode()
  70 +
  71 +# for test
  72 +if __name__ == "__main__":
  73 + api = QcloudApi(secretId='AK**K', secretKey='AC**QaW')
  74 + api.do_query(params={'Action': 'DescribeLoadBalancers'}, req_url=QcloudApi.URLS_lb)
  75 +
  76 +
  77 +
  78 +
  79 +
  80 +
  81 +
  82 +