modify_dsa_origin 6.91 KB
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# ansible module for DSA origin modify
ANSIBLE_METADATA = {
    'metadata_version': '1.0',
    'status': ['preview'],
    'supported_by': 'tiexin.yang'
}

DOCUMENTATION = '''
---
module: modify_dsa_origin
short_description:  修改静态加速DSA自有源站地址
'''

EXAMPLES = '''

- hosts: localhost
  tasks:
    - name: "修改DSA switch.test.yohops.com自有源站到指定地址"
      modify_dsa_origin:
        domain_name: "switch.test.yohops.com"
        new_origin: "java-public-lb-862332839.cn-north-1.elb.amazonaws.com.cn"
'''

from ansible.module_utils.basic import *
from ansible.module_utils.qcloud_api import QcloudApi
import requests
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')


'''
 检查当前DSA源站地址
'''

def get_dsa_id(SecretId,SecretKey,domain_name):
    ret = {}
    #腾讯云DSA资源接口请求URL
    dsa_api_url = 'dsa.api.qcloud.com/v2/index.php'
    api = QcloudApi(secretId=SecretId, secretKey=SecretKey)
    try:
        rsp = api.do_query(params={'Action': 'GetDsaHostList'}, req_url=dsa_api_url)
        #公共错误码,0表示成功,其他值表示失败
        ret["code"] = rsp["code"]
        #API请求返回错误信息
        ret["message"] = rsp["message"] if rsp["message"] else rsp["codeDesc"]
        #查询DSA源站配置
        if rsp["data"]["hosts"]:
            for dsa_host in rsp["data"]["hosts"]:
                if dsa_host["host"] == domain_name:
                    ret["host_id"] = dsa_host["host_id"]
                    ret["host"] = dsa_host["host"]
                    #匹配到对应域名则返回结果
                    return ret
                else:
                    continue
            #遍历hosts无匹配域名则返回错误信息
            ret["code"] = -1
            ret["message"] = "未找到{}的DSA配置信息,请检查输入域名!".format(domain_name)
        else:
            #返回hosts为空说明该账户下无dsa配置
            ret["code"] = -1
            ret["message"] = "当前账户下无DSA域名"
    except Exception as e:
        #捕捉请求超时等网络问题
        ret["code"] = -1
        ret["message"] = e.message
    return ret

def get_dsa_info(SecretId,SecretKey,dsa_id):
    ret = {}
    #腾讯云DSA资源接口请求URL
    dsa_api_url = 'dsa.api.qcloud.com/v2/index.php'
    api = QcloudApi(secretId=SecretId, secretKey=SecretKey)
    try:
        rsp = api.do_query(params={'Action': 'GetDsaHostInfo', 'hostId': dsa_id}, req_url=dsa_api_url)
        #公共错误码,0表示成功,其他值表示失败
        ret["code"] = rsp["code"]
        #API请求返回错误信息
        ret["message"] = rsp["message"] if rsp["message"] else rsp["codeDesc"]
        if ret["code"] == 0:
            #查询DSA源站配置
            dsa_info = rsp["data"]
            ret["host_id"] = dsa_info["host_id"]
            ret["host"] = dsa_info["host"]
            ret["cname"] = dsa_info["cname"]
            ret["status"] = dsa_info["status"]
            ret["origin"] = dsa_info["origin"]
            ret["fwd_host"] = dsa_info["fwd_host"]
            ret["locked"] = dsa_info["locked"]
            return ret
    except Exception as e:
        #捕捉请求超时等网络问题
        ret["code"] = -1
        ret["message"] = e.message
    return ret



def modify_origin(SecretId,SecretKey,dsa_id,new_origin):

    ret = {}
    #腾讯云DSA资源接口请求URL
    dsa_api_url = 'dsa.api.qcloud.com/v2/index.php'
    api = QcloudApi(secretId=SecretId, secretKey=SecretKey)
    try:
        #修改源站到目标自有源站地址
        rsp = api.do_query(params={'Action': 'UpdateDsaHostInfo', 'hostId': dsa_id, 'origin': new_origin}, req_url=dsa_api_url)
        ret["code"] = rsp["code"]
        ret["message"] = rsp["message"] if not rsp["message"] else rsp["codeDesc"]
    except Exception as e:
        ret["code"] = -1
        ret["message"] = e.message
    return ret
        

def run_module():

    #  定义参数
    module_args = dict(
        secretId=dict(type='str', required=True),
        secretKey=dict(type='str', required=True),
        domain_name=dict(type='str', required=True),
        new_origin=dict(type='str', required=True),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        original_message='',
        message=''
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )
    
    domain_name = module.params['domain_name']
    new_origin = module.params['new_origin']
    secretId = module.params['secretId']
    secretKey = module.params['secretKey']


    result['domain_name'] = module.params['domain_name']
    result['changed'] = False

    # 获取DSA hostId
    dsaid_ret = get_dsa_id(SecretId=secretId,SecretKey=secretKey,domain_name=domain_name)
    # 检查返回码
    if dsaid_ret["code"] == 0:
        dsa_id = dsaid_ret['host_id']
    else:
        module.fail_json(msg='DSA origin modification check Failed: return code:{0}, err: {1}'.format(dsaid_ret['code'], dsaid_ret['message']), **result)

    # 获取DSA 配置
    dsainfo_ret = get_dsa_info(SecretId=secretId,SecretKey=secretKey,dsa_id=dsa_id)
    if dsainfo_ret['code'] != 0:
        module.fail_json(msg='DSA origin modification check Failed: return code:{0}, err: {1}'.format(dsainfo_ret['code'], dsainfo_ret['message']), **result)
    # 检查锁定状态
    elif dsainfo_ret['locked'] == 1:
        module.fail_json(msg='DSA origin modification check Failed: return code:{0}, err: DSA运维锁已锁定,需要提交工单审核后才能修改'.format(dsainfo_ret['code']), **result)
    # 目标源站地址不能为空
    elif not new_origin.strip(' '):
        module.fail_json(msg='DSA origin modification check Failed: return code:{0}, err: 目标源站地址不能为空'.format(dsainfo_ret['code']), **result)
    else:
        result['message'] = {"DSA域名":domain_name, "DSA id":dsa_id, "当前自有源地址":dsainfo_ret['origin'], "目标自有源地址":new_origin}


    if module.check_mode:
        # check mode
        module.exit_json(**result)
    else:
        # 执行修改
        ret = modify_origin(SecretId=secretId,SecretKey=secretKey,dsa_id=dsa_id,new_origin=new_origin)
        if ret['code'] != 0:
            module.fail_json(msg='DSA origin modification Failed: return code:{0}, err: {1}'.format(ret['code'], ret['message']), **result)
        else:
            # 修改成功后输出前后对比
            ret['old_origin'] = dsainfo_ret['origin']
            ret['new_origin'] = new_origin
            result['changed'] = True
        result['response'] = ret
        module.exit_json(**result)

def main():
    run_module()

if __name__ == '__main__':
    main()