python 调用阿里云云解析api添加记录

首先安装阿里云SDK

pip install aliyun-python-sdk-core

pip install aliyun-python-sdk-alidns

可以配合jenkins传递参数

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/24 0024 13:42
# @Author  : sanmuyan
# @FileName: aliyun_domain_des.py
import json,jsonpath,os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109 import DescribeDomainRecordsRequest
from aliyunsdkalidns.request.v20150109 import AddDomainRecordRequest
from aliyunsdkalidns.request.v20150109 import DeleteDomainRecordRequest
from aliyunsdkalidns.request.v20150109 import DescribeDomainRecordInfoRequest

AccessKey = os.environ.get('AccessKey')
Secret = os.environ.get('Secret')
Regions = os.environ.get('Regions')
# 创建 AcsClient 实例
client = AcsClient(
    AccessKey,
    Secret,
    Regions
);

def dns_des(RecordId):
    request = DescribeDomainRecordInfoRequest.DescribeDomainRecordInfoRequest()
    request.set_RecordId(RecordId)
    response = client.do_action_with_exception(request)
    data = json.loads(response)
    data = json.dumps(data, sort_keys=True, indent=2)
    print(data)


def dns_del(DomainName, RR):
    request = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()
    request.set_DomainName(DomainName)
    request.set_RRKeyWord(RR)
    response = client.do_action_with_exception(request)
    data = json.loads(response)
    TotalCount = jsonpath.jsonpath(data,"$..TotalCount")
    if TotalCount[0] != 0:
        data1 = jsonpath.jsonpath(data,"$..RR")
        data2 = jsonpath.jsonpath(data,"$..RecordId")
        if RR in data1:
            index = data1.index(RR)
            RecordId = data2[index]
            print("WARNING: Delete the existing records")
            dns_des(RecordId)
            request = DeleteDomainRecordRequest.DeleteDomainRecordRequest()
            request.set_RecordId(RecordId)
            response = client.do_action_with_exception(request)
            return response

def dns_add(DomainName, RR, Type, Value):
    dns_del(DomainName, RR)
    request = AddDomainRecordRequest.AddDomainRecordRequest()
    request.set_DomainName(DomainName)
    request.set_RR(RR)
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)
    data = json.loads(response)
    print("INFO: Record adding success")
    RecordId = (data['RecordId'])
    dns_des(RecordId)


if __name__ == '__main__':
    DomainName = os.environ.get('DomainName')
    RR = os.environ.get('RR')
    Type = os.environ.get('Type')
    Value = os.environ.get('Value')
    dns_add(DomainName, RR, Type, Value)

 

posted @ 2018-01-25 15:42  三木燕  阅读(1181)  评论(0编辑  收藏  举报