This topic describes how to clone a Server Load Balancer (SLB) instance by using the Alibaba Cloud SDK for Python.

Prerequisites

Make sure that you have created two ECS instances in the China North 3 (Zhangjiakou) region and the two instances are in the Running state.

Background information

In this topic, the process for cloning an SLB instance is as follows:
  1. Create an SLB instance in China North 3 (Zhangjiakou), set its name to SLB1, set the primary zone to cn-zhangjiakou-a, set the backup zone to cn-zhangjiakou-b, set the billing method to Pay-As-You-Go, and set the specification to slb.s1.small. Use the default values for other parameters.
  2. Add the two ECS instances to the default server group of the created SLB instance and set the weight of both to 100.
  3. Create a TCP listener. Set the frontend port and backend port to 80, set the health check protocol to TCP, and do not set a peak bandwidth. Use the default values for other parameters.
  4. Query the details of SLB1.
  5. Create a clone SLB instance by copying the configurations of SLB1.
  6. Delete the instance SLB1.
  7. Query the details of the clone instance.
  8. Delete the clone instance.

Procedure

  1. From the downloaded SDK package, open the folder $aliyun-openapi-python-sdk-examples\sdk_examples\examples\slb.
  2. Open configration_clone.py by using an editor. Set the user authentication parameter ACS_CLIENT and other parameters as needed, save the file, and exit.
    Note Because the identity of a user must be authenticated by the SDK, you can also set the AcsClient parameter in the constants file and call the constants file when needed.
    #encoding=utf-8
    """
    Create an SLB instance->Create a TCP listener->Query details of the SLB instance->Clone the SLB instance->Delete the SLB instance
    """
    import sys
    import json
    import uuid
    
    #Call the AcsClient parameter for authentication.
    from aliyunsdkcore.client import AcsClient
    #Use the exception handling module of the Alibaba Cloud SDK.
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    #Redirect command line output.
    from sdk_lib.common_util import CommonUtil
    #Handle exceptions.
    from sdk_lib.exception import ExceptionHandler
    #Call the API used to create an SLB instance.
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerRequest
    #Call the API used to add a default server group.
    from aliyunsdkslb.request.v20140515 import AddBackendServersRequest
    #Call the API used to create a TCP listener.
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerTCPListenerRequest
    #Call the API used to query details of an SLB instance.
    from aliyunsdkslb.request.v20140515 import DescribeLoadBalancerAttributeRequest
    #Call the API used to create an SLB instance to clone the instance.
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerRequest
    #Call the API used to delete an SLB instance.
    from aliyunsdkslb.request.v20140515 import DeleteLoadBalancerRequest
    
    #Set the user authentication parameter.
    ACS_CLIENT = AcsClient(
        'your-access-key-id',     #your-access-key-id
        'your-access-key-secret',   #your-access-key-secret
        'cn-zhangjiakou',     #your-region-id
    )
    #The maximum number of retry times after a failture.
    TRY_TIME = 3
    
    def create_load_balancer(params):
        '''
        create_load_balancer:Create an SLB instance. 
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27577.htm?spm=a2c63.l28256.b99.137.78e67f8coB6lmm.
        '''
        try:
        #Set the API parameters for creating an SLB instance.
        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())) 
        #Send the request and receive the response.
        response = ACS_CLIENT.do_action_with_exception(request)
        response_json = json.loads(response)
        #Return results.    
        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:Add backend servers.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27632.htm?spm=a2c63.p38356.b99.168.7c37108bc4Jv0X.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
            #Set the API parameters for adding a default sever group.
                request = AddBackendServersRequest.AddBackendServersRequest()
                #The ID of the SLB instance 
                request.set_LoadBalancerId(params["load_balancer_id"])
                #A list of the backend servers to be added 
                request.set_BackendServers(params["backend_servers"])
                request.set_ClientToken(str(uuid.uuid1()))
            #Send the request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
            #Return results.
                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:Create a TCP listener.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27594.htm?spm=a2c63.p38356.b99.153.7bd544c7wLhqEj.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                #Set the API parameters for creating a TCP lisener.
                request = CreateLoadBalancerTCPListenerRequest.CreateLoadBalancerTCPListenerRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
            #The frontend port of the SLB instance 
                request.set_ListenerPort(params["listener_port"])
                #The backend port of the SLB instance 
                request.set_BackendServerPort(params["backend_server_port"])
            #The health check protocol of the listener 
                request.set_HealthCheckType(params["listener_health_check"])
            #The peak bandwidth of the listener 
                request.set_Bandwidth(params["listener_bandwidth"])
                request.set_ClientToken(str(uuid.uuid1()))
            #Send the request and receive the response. 
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
            #Return results.
                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
    
    #Query details of an SLB instance.
    def describe_load_balancer_attribute(params):
        '''
        describe_load_balancer_attribute:Query the details of a specified SLB instance.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27583.htm?spm=a2c63.p38356.b99.142.5cad77f9qy3u0j.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
                #The ID of the SLB instance
                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
    
    #Clone an SLB instance.
    def create_load_balancer_clone(params):
        '''
        create_load_balancer:Create an SLB instance.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27577.htm?spm=a2c63.l28256.b99.137.78e67f8coB6lmm.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = CreateLoadBalancerRequest.CreateLoadBalancerRequest()
                #The primary zone of the SLB instance
                request.set_MasterZoneId(params["master_zone_id"])
                #The backup zone of the SLB instance
                request.set_SlaveZoneId(params["slave_zone_id"])
                #The billing method
                request.set_PayType(params["pay_balancer_type"])
                #The ID of the resource group
                request.set_ResourceGroupId(params["resource_group_id"])
                #The IP version of the SLB instance
                request.set_AddressIPVersion(params["address_ip_version"])
                #The network type of the SLB instance
                request.set_AddressType(params["address_type"])
                #The name of the SLB instance
                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:Delete an SLB instance.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27579.htm?spm=a2c63.p38356.b99.138.58dd5708DguBv9.
        '''
        try:
        #Set the API parameters for deleting an SLB instance.
            request = DeleteLoadBalancerRequest.DeleteLoadBalancerRequest()
            #The ID of the SLB instance
            request.set_LoadBalancerId(load_balancer_id)
            #Send the request and receive the response.
            response = ACS_CLIENT.do_action_with_exception(request)
            response_json = json.loads(response)
        #Return results.
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
    
    def main():
        params = {}
        #Set parameters for the SLB instance.
        #Set the primary zone of the SLB instance to cn-zhangjiakou-a. 
        params["master_zone_id"] = "cn-zhangjiakou-a" 
        #Set the backup zone of the SLB instance to cn-zhangjiakou-b. 
        params["slave_zone_id"] = "cn-zhangjiakou-b" 
        #Set the name of the SLB instance to SLB1. 
        params["load_balancer_name"] = "SLB1"
        #Set the billing method of the SLB instance to Pay-As-You-Go.
        params["pay_balancer_type"] = "PayOnDemand"
        #Set the specification of the SLB instance to slb.s1.small.
        params["load_balancer_spec"] = "slb.s1.small"
        
        #Set IDs and weights of the ECS instances added to the default server group.
        params["backend_servers"] = [{"ServerId":"i-8vxxxxx","Weight":"100"},{"ServerId":"i-8vbe8xxxxxxxv","Weight":"100"}]
        
        #Set parameters for the TCP listener.
        #Set the frontend port to 80.
        params["listener_port"] = 80
        #Set the backend port for receiving requests to 80.
        params["backend_server_port"] = 80
        #Set the health check protocol to TCP.
        params["listener_health_check"] = "tcp"
        #Set the peak bandwidth of the TCP listener to -1, which means the peak bandwidth is not limited.
        params["listener_bandwidth"] = -1
    
        #Create an SLB instance.
        #Obtain the returned value of create_load_balancer. "load_balancer_json" is the returned value in json format.
        result_json = create_load_balancer(params)
        #Print the returned value of load_balancer_json, where "create_load_balancer" is the name of the json string.
        CommonUtil.log("create_load_balancer", result_json)
        
        #Read the ID and name of the SLB instance.
        load_balancer_id = result_json["LoadBalancerId"]
        params["load_balancer_id"] = load_balancer_id
        params["LoadBalancerName"] = result_json["LoadBalancerName"]
    
        #Create a TCP listener.
        result_json = create_tcp_listener(params)
        CommonUtil.log("create_tcp_listener", result_json)
    
        #Query details of the SLB instance.
        result_json = describe_load_balancer_attribute(params)
        CommonUtil.log("describe_load_balancer_attribute", result_json)
        #The information that you require about the SLB instance
        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"]
        
        #Create a clone instance by copying the configurations of the SLB instance.
        result_json = create_load_balancer_clone(params)
        CommonUtil.log("create_load_balancer_clone", result_json)
        
        #Read the ID of the clone instance.
        clone_load_balancer_id = result_json["LoadBalancerId"]
        
        #Delete the SLB instance you first created.
        #Delete the SLB instance that the returned LoadBalancerId indicates.
        result_json = delete_load_balancer(load_balancer_id)
        #Print the returned value of load_balancer_json.
        CommonUtil.log("delete_load_balancer", result_json)
        
        #Query the details of the clone instance.
        params["load_balancer_id"] = clone_load_balancer_id
        result_json = describe_load_balancer_attribute(params)
        CommonUtil.log("describe_load_balancer_attribute", result_json)
        
    
        #Delete the clone instance.
        #Delete the SLB instance that the returned LoadBalancerId indicates.
        result_json = delete_load_balancer(clone_load_balancer_id)
        #Print the returned value of load_balancer_json.
        CommonUtil.log("delete_load_balancer", result_json)
    
    if __name__ == "__main__":
        sys.exit(main())
  3. Go to the configration_clone.py directory and run the following command to clone the instance.
    python configration_clone.py
    If the following output is displayed, the SLB instance is cloned and then deleted:
    ---------------------------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"
    }