Jenkins+Python調用阿里雲API實現發佈自動修改SLB權重

  • 需求
    目前線上環境系統經過Jenkins發佈時,需先將發佈的ECS實例手動下線,即在阿里雲SLB手動修改權重爲0。而後在Jenkins中發佈構建,發佈完成後,又在SLB上手動修改權重。現爲了省去每次登陸阿里雲SLB控制檯,手動修改SLB權重這一繁瑣的手動操做。現經過調用阿里雲SLB的API結合Python程序去實現,經過API實現對SLB下的ECS實例的下線、移除、增長等操做,實際狀況用的比較多的是對ECS下線操做,即修改SLB下對應的ECS實例權重。
    開始實戰操做:
  • 環境
    Jenkins
    Python3.8
    CentOS7
    這裏附上Python3.8的安裝:
    #CentOS7 源碼編譯安裝Python3.8
    安裝依賴:
    yum install gcc openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel libffi-devel tk-devel wget curl-devel
    下載:
    wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz
    解壓:
    tar -xzvf Python-3.8.0.tgz
    編譯安裝:
    mkdir /usr/local/python3
    /root/Python-3.8.0
    ./configure --prefix=/usr/local/python3/
    make && make install
    創建軟連接:
    ln -s /usr/local/python3/bin/python3 /usr/bin/python3
    ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3
  • 調用阿里雲API
    需先安裝sdk模塊
    安裝 aliyun-python-sdk-core-v3
    Jenkins+Python調用阿里雲API實現發佈自動修改SLB權重
    安裝 aliyun-python-sdk-slb
    Jenkins+Python調用阿里雲API實現發佈自動修改SLB權重
    關鍵的python腳本以下:
#!/usr/bin/env python
#-*-coding:utf-8 -*-
#@Time     : 2020/06/16
#@Author   : Joey

import sys
import json

from aliyunsdkcore.client import AcsClient
from aliyunsdkslb.request.v20140515 import DescribeLoadBalancersRequest
from aliyunsdkslb.request.v20140515 import DescribeLoadBalancerAttributeRequest
from aliyunsdkslb.request.v20140515 import SetBackendServersRequest
from aliyunsdkslb.request.v20140515 import AddBackendServersRequest
from aliyunsdkslb.request.v20140515 import RemoveBackendServersRequest

#Access Key 信息
AccessKey = 'ak'
AccessKeySecret = 'ak123'
RegionId = 'cn-shanghai'

client = AcsClient(AccessKey, AccessKeySecret, RegionId)

Info = '''
Basic Commands :
  get            獲取SLB信息
  edit           配置SLB的後端權重
  add            添加SLB的後端實例
  remove         刪除SLB的後端實例
Usage:
    獲取全部實例的信息
        python slb.py get all
    獲取某一實例的信息
        python slb.py get lb-uf6rb7g4a3op3f1qi19yx
    編輯單個權重
        python slb.py edit lb-uf6rb7g4a3op3f1qi19yx [{\"ServerId\":\"i-ecs\",\"Weight\":\"95\",\"ServerIp\":\"10.10.10.10\",\"Type\":\"ecs\"}]
    編輯多個權重(最多20個)
        python slb.py edit lb-uf6rb7g4a3op3f1qi19yx [{"ServerId":"i-ecs1","Weight":"100"},{"ServerId":"i-ecs2","Weight":"100"}]
    添加單個後端ecs
        python slb.py add lb-uf6rb7g4a3op3f1qi19yx [{"ServerId":"i-ecs01","Weight":"100"}]
    添加多個後端ecs
        python slb.py add lb-uf6rb7g4a3op3f1qi19yx [{"ServerId":"i-ecs01","Weight":"100"},{"ServerId":"i-ecs02","Weight":"100"}]
    刪除單個後端ecs
        python slb.py remove lb-uf6rb7g4a3op3f1qi19yx [{"ServerId":"i-ecs01","Weight":"100"}]
    刪除多個後端ecs
        python slb.py remove lb-uf6rb7g4a3op3f1qi19yx [{"ServerId":"i-ecs01","Weight":"100"},{"ServerId":"i-ecs02","Weight":"100"}]
'''

def InfoSLB():
    print(Info)

def DescribeLoadBalancers(resource):
    request = DescribeLoadBalancersRequest.DescribeLoadBalancersRequest()   #SLB實例列表
    response = client.do_action_with_exception(request)    #發起請求
    SLBInfo = json.loads(response)  #處理 response  Json字符串對象
    LoadBalancerIdList = []
    for SLBInstance in SLBInfo['LoadBalancers']['LoadBalancer']:    #LoadBalancers 返回負載均衡實例列表, LoadBalancer 負載均衡實例
        LoadBalancerIdList.append(SLBInstance['LoadBalancerId'])    #經過 LoadBalancerId 獲得 SLB實例
        print("SLBInstance實例詳細信息: %s " % SLBInstance)

    if resource == 'all':
        Ali_Slb_Info = {}
        for SLBInstance in SLBInfo['LoadBalancers']['LoadBalancer']:    #SLB 實例
            request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()   #SLB實例詳細信息
            request.set_LoadBalancerId(SLBInstance['LoadBalancerId'])
            #request.get_LoadBalancerId()
            response = client.do_action_with_exception(request)
            Ali_Slb_Info[SLBInstance['LoadBalancerId']] = json.loads(response.decode('utf-8'))    #Json字符串 反序列化成 python對象, SLB實例列表 存儲到set
        print(LoadBalancerIdList)
        # print(Ali_Slb_Info[SLBInstance['LoadBalancerId']])
    elif resource in LoadBalancerIdList:
        request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
        request.set_LoadBalancerId(resource)    #某一SLB實例詳細信息
        response = client.do_action_with_exception(request)
        response = json.loads(response.decode('utf-8'))
        print("SLB後端ECS服務器列表: %s " % response['BackendServers'])    #SLB後端服務器列表
    else:
        print("輸入錯誤,請輸入 all 或 SLB實例ID !")

#設置SLB後端服務器權重等信息
def SetBackendServers(resource,BackendServers):
    request = SetBackendServersRequest.SetBackendServersRequest()    #調用SetBackendServers設置後端服務器權重、Port、ECS等信息
    request.set_accept_format('json')
    request.set_BackendServers(BackendServers)
    request.set_LoadBalancerId(resource)
    print("後端ECS信息: %s" % BackendServers)
    response = client.do_action_with_exception(request)
    print("SLB返回結果爲: %s" % str(response, encoding='utf-8'))

#增長SLB後端實例
def AddBackendServers(resource,BackendServers):
    request = AddBackendServersRequest.AddBackendServersRequest()    #調用 AddBackendServersRequest 調整增長後端實例
    request.set_accept_format('json')
    request.set_BackendServers(BackendServers)
    request.set_LoadBalancerId(resource)

    response = client.do_action_with_exception(request)
    print(str(response, encoding='utf-8'))

#移除SLB後端實例
def RemoveBackendServers(resource,BackendServers):
    request = RemoveBackendServersRequest()
    request.set_accept_format('json')
    request.set_BackendServers(BackendServers)
    request.set_LoadBalancerId(resource)

    response = client.do_action_with_exception(request)
    print(str(response, encoding='utf-8'))

if __name__ == '__main__':
    if len(sys.argv) == 1:
        main()
    else:
        userInput = sys.argv[1:]
        if userInput[0] == 'get' and userInput[1]:    #userInput[1] LoadBalancerId or all
            resource = userInput[1]
            print("SLB實例ID: %s " % resource)
            DescribeLoadBalancers(resource)
        elif userInput[0] == 'edit' and userInput[1] and userInput[2]:    #userInput[1] LoadBalancerId; userInput[2] BackendServers
            resource = userInput[1]
            BackendServers = userInput[2]
            print("編輯的SLB實例ID: %s " % resource)
            print("編輯後端ECS,傳入的參數信息: %s " % BackendServers)
            SetBackendServers(resource, BackendServers)
        elif userInput[0] == 'add' and userInput[1] and userInput[2]:
            resource = userInput[1]
            BackendServers = userInput[2]
            AddBackendServers(resource, BackendServers)
        elif userInput[0] == 'remove' and userInput[1] and userInput[2]:
            resource = userInput[1]
            BackendServers = userInput[2]
            RemoveBackendServers(resource, BackendServers)
        else:
            print("錯誤的輸入!")
相關文章
相關標籤/搜索