This topic describes how to create a TCP listener for a Server Load Balancer (SLB) instance and then delete the 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 creating a TCP listener and then deleting the 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. After the TCP listener is created, remove the two ECS instances from the default server group.
  5. Delete the SLB instance.

Procedure

  1. From the downloaded SDK package, open the folder $aliyun-openapi-python-sdk-examples\sdk_examples\examples\slb.
  2. Open slb_create_tcp_listener.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->Add backend servers->Create a TCP listener->Remove backend servers->Delete the SLB instance
    """
    import json
    import sys
    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
    #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 add a TCP listener.
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerTCPListenerRequest
    #Call the API used to remove ECS instances from the default server group.
    from aliyunsdkslb.request.v20140515 import RemoveBackendServersRequest
    #Call the API used to delete an SLB instance.
    from aliyunsdkslb.request.v20140515 import DeleteLoadBalancerRequest
    #Redirect command line output.  
    from sdk_lib.common_util import CommonUtil
    #Handle exceptions.
    from sdk_lib.exception import ExceptionHandler
    
    #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
    )
    
    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.p38356.b99.137.1ce71093wjK1an.
        '''
        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.7f08108b8AKVSn.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
            #Set the API parameters for adding a default server 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.266c44c7617Cpt.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
            #Set the API parameters for creating a TCP listener.
                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"])
            #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 remove_backend_servers(params):
        '''
        add_backend_servers:Remove backend servers.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27633.htm?spm=a2c63.p38356.b99.169.5ae177f98SAy0s.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
            #Set the API parameters for removing backend servers.
                request = RemoveBackendServersRequest.RemoveBackendServersRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
                #A list of the backend servers to be removed
                request.set_BackendServers(params["backend_servers"])
                #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 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.50d5108biWok5Y.
        '''
        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-8vbe8yi8krxxxxxxxxxxw","Weight":"100"},{"ServerId":"i-8vbe8yi8kccxxxxxxxxxv","Weight":"100"}]
    
        #Set parameters for the TCP listener.
        #Set the frontend port to 80.
        params["listener_port"] = 80
        #Set the backup 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 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.
        load_balancer_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", load_balancer_json)
    
        #The ID of the SLB instance
        params["load_balancer_id"] = load_balancer_json["LoadBalancerId"]
    
        #Add backend servers.
        load_balancer_json = add_backend_servers(params)
        CommonUtil.log("add_backend_servers", load_balancer_json)
    
        #Create a TCP listener.
        load_balancer_json = create_tcp_listener(params)
        CommonUtil.log("create_tcp_listener", load_balancer_json)
    
        #Delete backend servers.
        load_balancer_json = remove_backend_servers(params)
        CommonUtil.log("remove_backend_servers", load_balancer_json)
    
        #Delete an SLB instance.
        #Delete the SLB instance that the returned LoadBalancerId indicates.
        load_balancer_json = delete_load_balancer(load_balancer_json["LoadBalancerId"])
        #Print the returned value of load_balancer_json.
        CommonUtil.log("delete_load_balancer", load_balancer_json)
    
    
    if __name__ == "__main__":
        sys.exit(main())
  3. Go to the slb_create_tcp_listener.py directory and run the following command to create a TCP listener.
    python slb_create_tcp_listener.py
    If the following output is displayed, a TCP listener is created and the SLB instance is removed:
    ---------------------------create_load_balancer---------------------------
    {
      "VpcId": "",
      "AddressIPVersion": "ipv4",
      "LoadBalancerName": "SLB1",
      "ResourceGroupId": "rg-acfmxazb4pxxxxx",
      "VSwitchId": "",
      "RequestId": "8E72DFDD-E510-4D65-9063-F47B62DE9887",
      "Address": "39.98.xx.xx",
      "NetworkType": "classic",
      "LoadBalancerId": "lb-8vbjd6pzphvjoq29xxxxx"
    }
    
    ---------------------------add_backend_servers---------------------------
    {
      "RequestId": "F6BF0E0B-5837-48A3-9CEC-2EE2CED5293A",
      "BackendServers": {
        "BackendServer": [
          {
            "ServerId": "i-8vbe8yi8krqri2axxxxx",
            "Type": "ecs",
            "Weight": 100
          },
          {
            "ServerId": "i-8vbe8yi8krqri2xxxxxx",
            "Type": "ecs",
            "Weight": 100
          }
        ]
      },
      "LoadBalancerId": "lb-8vbjd6pzphvjoq29xxxxx"
    }
    
    ---------------------------create_tcp_listener---------------------------
    {
      "RequestId": "6FF090BD-DF9F-49C6-84A6-30F2D9F88489"
    }
    
    ---------------------------remove_backend_servers---------------------------
    {
      "RequestId": "F7D62969-D7F0-4022-95FA-1710DA448B6A",
      "BackendServers": {
        "BackendServer": []
      },
      "LoadBalancerId": "lb-8vbjd6pzphvjoq29xxxxx"
    }
    
    ---------------------------delete_load_balancer---------------------------
    {
      "RequestId": "1A8CB48F-8242-49A9-9958-E762B1E9BA4D"
    }