介绍如何使用Python SDK克隆SLB实例。

前提条件

在华北3张家口地域已经有两台状态为运行中的ECS实例。

背景信息

本次示例分为以下几步,克隆SLB实例:
  1. 在华北3张家口地域创建一个名为SLB1的SLB实例,主可用区为cn-zhangjiakou-a,备可用区为cn-zhangjiakou-b,实例计费类型为按量计费,规格为slb.s1.small,其他配置使用系统默认值。
  2. 将张家口地域的两台ECS实例添加到默认服务器组,用来分发流量,ECS实例的后端服务权重都为100。
  3. 创建TCP监听,SLB实例前端使用的端口为80,后端服务器开放用来接收请求的端口为80,健康检查协议为TCP,不限制监听带宽峰值,其他使用默认值。
  4. 查询实例SLB1的信息,作为克隆实例的入参。
  5. 克隆新的SLB实例。
  6. 删除SLB1实例。
  7. 查询克隆实例的信息。
  8. 删除克隆实例。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\slb文件夹。
  2. 使用编辑器打开configration_clone.py文件,您需要配置用户鉴权参数ACS_CLIENT,其他参数根据实际情况配置后,保存退出。
    说明 因为用户鉴权是每个SDK必须执行的操作,所以可以在常量文件中配置AcsClient参数的值,在场景代码中调用常量文件。
    #encoding=utf-8
    """
    创建slb实例->添加tcp监听->查询slb实例->slb实例克隆->删除slb实例
    """
    import sys
    import json
    import uuid
    
    #调用AcsClient参数进行身份验证
    from aliyunsdkcore.client import AcsClient
    #使用阿里云官方sdk的异常处理模块
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    #命令行打印日志
    from sdk_lib.common_util import CommonUtil
    #异常处理逻辑
    from sdk_lib.exception import ExceptionHandler
    #调用创建SLB实例API   
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerRequest
    #调用添加默认服务器组API
    from aliyunsdkslb.request.v20140515 import AddBackendServersRequest
    #调用添加TCP监听API
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerTCPListenerRequest
    #调用查询SLB实例信息API
    from aliyunsdkslb.request.v20140515 import DescribeLoadBalancerAttributeRequest
    #调用创建SLB实例API克隆实例
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerRequest
    #调用删除SLB实例API  
    from aliyunsdkslb.request.v20140515 import DeleteLoadBalancerRequest
    
    #用户身份验证参数配置
    ACS_CLIENT = AcsClient(
        'your-access-key-id',     #your-access-key-id
        'your-access-key-secret',   #your-access-key-secret
        'cn-zhangjiakou',     #your-region-id
    )
    #失败重试次数
    TRY_TIME = 3
    
    def create_load_balancer(params):
        '''
        create_load_balancer:创建slb实例
    
        '''
        try:
        #设置创建SLB实例的调用参数
        request = CreateLoadBalancerRequest.CreateLoadBalancerRequest() 
        request.set_MasterZoneId(params["master_zone_id"]) 
        request.set_SlaveZoneId(params["slave_zone_id"]) 
        request.set_LoadBalancerName(params["load_balancer_name"]) 
        request.set_PayType(params["pay_balancer_type"]) 
            request.set_LoadBalancerSpec(params["load_balancer_spec"])
            request.set_ClientToken(str(uuid.uuid1())) 
        #发送调用请求并接收返回数据
        response = ACS_CLIENT.do_action_with_exception(request)
        response_json = json.loads(response)
        #返回结果    
        return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
    
    def add_backend_servers(params):
        '''
        add_backend_servers:添加后端服务器
    
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
            #设置添加默认服务器组的调用参数
                request = AddBackendServersRequest.AddBackendServersRequest()
                #负载均衡实例的ID
                request.set_LoadBalancerId(params["load_balancer_id"])
                #要添加的后端服务器列表
                request.set_BackendServers(params["backend_servers"])
                request.set_ClientToken(str(uuid.uuid1()))
            #发送调用请求并接收返回数据
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
            #返回结果
                return response_json
            except ServerException as e:
                if ExceptionHandler.server_exception(e):
                    return e
            except ClientException as e:
                if ExceptionHandler.client_exception(e):
                    return e
            finally:
                counter += 1
    
    def create_tcp_listener(params):
        '''
        create_tcp_listener:创建tcp监听
    
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                #设置创建TCP监听的调用参数
                request = CreateLoadBalancerTCPListenerRequest.CreateLoadBalancerTCPListenerRequest()
                #负载均衡实例的ID
                request.set_LoadBalancerId(params["load_balancer_id"])
            #负载均衡实例前端使用的端口
                request.set_ListenerPort(params["listener_port"])
                #负载均衡实例后端使用的端口
                request.set_BackendServerPort(params["backend_server_port"])
            #监听的健康检查协议
                request.set_HealthCheckType(params["listener_health_check"])
            #设置监听的带宽峰值
                request.set_Bandwidth(params["listener_bandwidth"])
                request.set_ClientToken(str(uuid.uuid1()))
            #发送调用请求并接收返回数据
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
            #返回结果
                return response_json
            except ServerException as e:
                if ExceptionHandler.server_exception(e):
                    return e
            except ClientException as e:
                if ExceptionHandler.client_exception(e):
                    return e
            finally:
                counter += 1
    
    #查询slb实例
    def describe_load_balancer_attribute(params):
        '''
        describe_load_balancer_attribute:查询指定负载均衡实例的详细信息
    
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
                #负载均衡实例的id
                request.set_LoadBalancerId(params["load_balancer_id"])
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
            finally:
                counter += 1
    
    #克隆slb实例
    def create_load_balancer_clone(params):
        '''
        create_load_balancer:创建slb实例
    
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = CreateLoadBalancerRequest.CreateLoadBalancerRequest()
                #主可用区
                request.set_MasterZoneId(params["master_zone_id"])
                #备可用区
                request.set_SlaveZoneId(params["slave_zone_id"])
                #付费类型
                request.set_PayType(params["pay_balancer_type"])
                #资源组id
                request.set_ResourceGroupId(params["resource_group_id"])
                #负载均衡实例的ip版本
                request.set_AddressIPVersion(params["address_ip_version"])
                #负载均衡实例的网络类型
                request.set_AddressType(params["address_type"])
                #实例名称
                request.set_LoadBalancerName(params["load_balancer_name"])
                request.set_ClientToken(str(uuid.uuid1()))
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
            finally:
                counter += 1
    def delete_load_balancer(load_balancer_id):
        '''
        delete_load_balancer:删除slb实例
    
        '''
        try:
        #设置删除SLB实例的调用参数
            request = DeleteLoadBalancerRequest.DeleteLoadBalancerRequest()
            #负载均衡实例的ID
            request.set_LoadBalancerId(load_balancer_id)
            #发送调用请求并接收返回数据
            response = ACS_CLIENT.do_action_with_exception(request)
            response_json = json.loads(response)
        #返回结果
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
    
    def main():
        params = {}
        #设置创建SLB实例的参数
        #设置新建SLB实例的主可用区为cn-zhangjiakou-a 
        params["master_zone_id"] = "cn-zhangjiakou-a" 
        #设置新建SLB实例的主可用区为cn-zhangjiakou-b 
        params["slave_zone_id"] = "cn-zhangjiakou-b" 
        #设置新建SLB实例的名称为SLB1 
        params["load_balancer_name"] = "SLB1"
        #设置新建SLB实例的计费类型为按量计费
        params["pay_balancer_type"] = "PayOnDemand"
        #设置新建SLB实例的规格为slb.s1.small
        params["load_balancer_spec"] = "slb.s1.small"
    
        #设置添加到默认服务器组的ECS的实例ID和权重
        params["backend_servers"] = [{"ServerId":"i-8vxxxxx","Weight":"100"},{"ServerId":"i-8vbe8xxxxxxxv","Weight":"100"}]
    
        #设置添加TCP监听的参数
        #前端使用的端口为80
        params["listener_port"] = 80
        #后端服务器开放用来接收请求的端口为80
        params["backend_server_port"] = 80
        #健康检查协议为TCP
        params["listener_health_check"] = "tcp"
        #TCP监听的带宽峰值为-1,即不限制带宽峰值
        params["listener_bandwidth"] = -1
    
        #创建slb实例
        #获取create_load_balancer函数返回值,load_balancer_json为结果的json串
        result_json = create_load_balancer(params)
        #打印 load_balancer_json结果,其中"create_load_balancer"是对json串起的名字
        CommonUtil.log("create_load_balancer", result_json)
    
        #读取新建SLB实例的ID和名称
        load_balancer_id = result_json["LoadBalancerId"]
        params["load_balancer_id"] = load_balancer_id
        params["LoadBalancerName"] = result_json["LoadBalancerName"]
    
        #创建tcp监听
        result_json = create_tcp_listener(params)
        CommonUtil.log("create_tcp_listener", result_json)
    
        #查询slb实例
        result_json = describe_load_balancer_attribute(params)
        CommonUtil.log("describe_load_balancer_attribute", result_json)
        #需要显示的查询新建SLB实例信息
        params["master_zone_id"] = result_json["MasterZoneId"]
        params["slave_zone_id"] = result_json["SlaveZoneId"]
        params["pay_balancer_type"] = result_json["PayType"]
        params["resource_group_id"] = result_json["ResourceGroupId"]
        params["address_ip_version"] = result_json["AddressIPVersion"]
        params["address_type"] = result_json["AddressType"]
        params["load_balancer_name"] = result_json["LoadBalancerName"]
    
        #根据SLB1的配置,克隆一个新的实例
        result_json = create_load_balancer_clone(params)
        CommonUtil.log("create_load_balancer_clone", result_json)
    
        #读取克隆实例ID
        clone_load_balancer_id = result_json["LoadBalancerId"]
    
        #删除第一个实例
        #删除返回的LoadBalancerId对应的SLB实例
        result_json = delete_load_balancer(load_balancer_id)
        #打印 load_balancer_json结果
        CommonUtil.log("delete_load_balancer", result_json)
    
        #查询克隆出来的实例信息
        params["load_balancer_id"] = clone_load_balancer_id
        result_json = describe_load_balancer_attribute(params)
        CommonUtil.log("describe_load_balancer_attribute", result_json)
    
    
        #删除克隆出来的实例
        #删除返回的LoadBalancerId对应的SLB实例
        result_json = delete_load_balancer(clone_load_balancer_id)
        #打印 load_balancer_json结果
        CommonUtil.log("delete_load_balancer", result_json)
    
    if __name__ == "__main__":
        sys.exit(main())
  3. 进入configration_clone.py所在的目录,执行如下命令,运行克隆实例示例。
    python configration_clone.py
    系统显示类似如下:
    ---------------------------create_load_balancer---------------------------
    {
      "VpcId": "",
      "AddressIPVersion": "ipv4",
      "LoadBalancerName": "SLB1",
      "ResourceGroupId": "rg-acfxxxxxxxxxxy",
      "VSwitchId": "",
      "RequestId": "544656CD-4DC9-47CB-B4DA-9371C0098F37",
      "Address": "39.xx.xx.xx",
      "NetworkType": "classic",
      "LoadBalancerId": "lb-8vbermxxxxxxxxx90l"
    }
    
    ---------------------------create_tcp_listener---------------------------
    {
      "RequestId": "4FCAFA1B-A6A8-4AA7-AB26-788C4F1506DA"
    }
    
    ---------------------------describe_load_balancer_attribute---------------------
    ------
    {
      "LoadBalancerStatus": "inactive",
      "HasReservedInfo": "false",
      "InternetChargeType": "paybytraffic",
      "EndTime": "2999-09-08T16:00:00Z",
      "VpcId": "",
      "RegionIdAlias": "cn-zhangjiakou",
      "RegionId": "cn-zhangjiakou",
      "ListenerPortsAndProtocal": {
        "ListenerPortAndProtocal": [
          {
            "ListenerPort": 80,
            "ListenerProtocal": "tcp"
          }
        ]
      },
      "ResourceGroupId": "rg-acfxxxxxxxaiy",
      "CreateTimeStamp": 1551254179000,
      "VSwitchId": "",
      "Address": "39.98.97.43",
      "AddressIPVersion": "ipv4",
      "LoadBalancerSpec": "slb.s1.small",
      "EndTimeStamp": 32493801600000,
      "ListenerPortsAndProtocol": {
        "ListenerPortAndProtocol": [
          {
            "ListenerProtocol": "tcp",
            "ListenerPort": 80
          }
        ]
      },
      "LoadBalancerId": "lb-8vxxxxxxxxxx90l",
      "AddressType": "internet",
      "RequestId": "9D696BEF-18C2-4EFD-92F4-434580964A51",
      "BackendServers": {
        "BackendServer": []
      },
      "MasterZoneId": "cn-zhangjiakou-a",
      "PayType": "PayOnDemand",
      "SlaveZoneId": "cn-zhangjiakou-b",
      "Bandwidth": 5120,
      "LoadBalancerName": "SLB1",
      "NetworkType": "classic",
      "CreateTime": "2019-02-27T07:56:19Z",
      "ListenerPorts": {
        "ListenerPort": [
          80
        ]
      }
    }
    
    ---------------------------create_load_balancer_clone---------------------------
    
    {
      "VpcId": "",
      "AddressIPVersion": "ipv4",
      "LoadBalancerName": "SLB1",
      "ResourceGroupId": "rg-acxxxxxxxxxxiy",
      "VSwitchId": "",
      "RequestId": "0E051B90-1C32-4270-A653-F7FBB03E3E5C",
      "Address": "xx.xx.xx.xx",
      "NetworkType": "classic",
      "LoadBalancerId": "lb-8xxxxxxxxxxxxxx"
    }
    
    ---------------------------delete_load_balancer---------------------------
    {
      "RequestId": "14703145-BC19-4032-A5F5-6DD49AED6885"
    }
    
    ---------------------------describe_load_balancer_attribute---------------------
    ------
    {
      "LoadBalancerStatus": "active",
      "HasReservedInfo": "false",
      "InternetChargeType": "paybytraffic",
      "EndTime": "2999-09-08T16:00:00Z",
      "VpcId": "",
      "RegionIdAlias": "cn-zhangjiakou",
      "RegionId": "cn-zhangjiakou",
      "ListenerPortsAndProtocal": {
        "ListenerPortAndProtocal": []
      },
      "ResourceGroupId": "rg-acfxxxxxxxxxiy",
      "CreateTimeStamp": 1551254182000,
      "VSwitchId": "",
      "Address": "39.98.97.36",
      "AddressIPVersion": "ipv4",
      "MasterZoneId": "cn-zhangjiakou-a",
      "EndTimeStamp": 32493801600000,
      "ListenerPortsAndProtocol": {
        "ListenerPortAndProtocol": []
      },
      "LoadBalancerId": "lb-8vxxxxxxxxxxx",
      "AddressType": "internet",
      "RequestId": "6345BAD4-B7EB-4280-9C7B-BB1324A77E32",
      "BackendServers": {
        "BackendServer": []
      },
      "PayType": "PayOnDemand",
      "SlaveZoneId": "cn-zhangjiakou-b",
      "Bandwidth": 5120,
      "LoadBalancerName": "SLB1",
      "NetworkType": "classic",
      "CreateTime": "2019-02-27T07:56:22Z",
      "ListenerPorts": {
        "ListenerPort": []
      }
    }
    
    ---------------------------delete_load_balancer---------------------------
    {
      "RequestId": "DC7C11D0-E21E-49AE-9695-F0171960D0F1"
    }