This topic describes how to use the Alibaba Cloud SDK for Python to associate an elastic IP address (EIP) with a Server Load Balancer (SLB) instance or an elastic network interface (ENI).

Prerequisites

Background information

The sample code includes the following operations:
  1. Create an SLB instance in the China (Hangzhou) region.
  2. Create an EIP in the China (Hangzhou) region.
  3. Associate the EIP with the SLB instance.
  4. Disassociate the EIP from the SLB instance.
  5. Associate the detached EIP with the ENI.
  6. Disassociate the EIP from the ENI.
  7. Deletes an SLB instance.

Procedure

  1. In the downloaded SDK directory, open the $aliyun-openapi-python-sdk-examples\sdk_examples\examples\eip folder.
  2. Open eip_associate_slb.py in your text editor. Set the parameters as required, save the configuration, and then exit the editor.
    The following sample code is displayed:
    #encoding=utf-8
    import sys
    import json
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    from aliyunsdkvpc.request.v20160428 import AllocateEipAddressRequest
    from aliyunsdkvpc.request.v20160428 import AssociateEipAddressRequest
    from aliyunsdkvpc.request.v20160428 import DescribeEipAddressesRequest
    from aliyunsdkvpc.request.v20160428 import UnassociateEipAddressRequest
    from aliyunsdkvpc.request.v20160428 import ModifyEipAddressAttributeRequest
    from aliyunsdkvpc.request.v20160428 import ReleaseEipAddressRequest
    from sdk_lib.exception import ExceptionHandler
    from sdk_lib.check_status import CheckStatus
    from sdk_lib.consts import *
    from sdk_lib.common_util import CommonUtil
    from sdk_lib.sdk_load_balancer import LoadBalancer
    
    """
    The sample code shows the following steps: 1. Create a VPC. 2. Create a VSwitch. 3. Call an ECS API operation to generate an ENI. These steps are not included in the following code.
    4. Create an SLB instance. 5. Create an EIP. 6. Associate the EIP with the SLB instance. 7. Disassociate the EIP from the SLB instance. 8. Associate the EIP with the ENI. 9. Disassociate the EIP from the SLB instance. 10. Delete the SLB instance.
    """
    class Eip(object):
        def __init__(self, client):
            self.client = client
    
        def allocate_eip_address(self, params):
            """
            allocate_eip_address: requests an EIP.
            """
            try:
                request = AllocateEipAddressRequest.AllocateEipAddressRequest()
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_eip_status,
                                            AVAILABLE, response_json["AllocationId"]):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def associate_eip_address(self, params):
            """
            allocate_eip_address: associates the EIP with the cloud service that is deployed in the same region.
            """
            try:
                request = AssociateEipAddressRequest.AssociateEipAddressRequest()
                # The ID of the EIP.
                request.set_AllocationId(params['allocation_id'])
                # The type of the cloud service with which the EIP is associated.
                request.set_InstanceType(params['instance_type'])
                # The ID of the instance with which the EIP is associated.
                request.set_InstanceId(params['instance_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_eip_status,
                                            InUse, params['allocation_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_eip_address(self, allocation_id):
            """
            describe_eip_status: queries the created EIPs in a specified region.
            """
            try:
                request = DescribeEipAddressesRequest.DescribeEipAddressesRequest()
                # The ID of the EIP.
                request.set_AllocationId(allocation_id)
                response = self.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 describe_eip_status(self, allocation_id):
            """
            describe_eip_status: queries the status of the created EIPs in a specified region
            """
            # The ID of the EIP.
            response = self.describe_eip_address(allocation_id)
            return response["EipAddresses"]["EipAddress"][0]["Status"]
    
    
        def unassociate_eip_address(self, params):
            """
            unassociate_eip_address: disassociates an EIP from a cloud resource.
            """
            try:
                request = UnassociateEipAddressRequest.UnassociateEipAddressRequest()
                # The ID of the EIP.
                request.set_AllocationId(params['allocation_id'])
                # The type of resource from which the EIP is disassociated.
                request.set_InstanceType(params['instance_type'])
                # The ID of the instance from which the EIP is disassociated.
                request.set_InstanceId(params['instance_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_eip_status,
                                            AVAILABLE, params['allocation_id']):
                    return response_json
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def modify_eip_address(self, params):
            """
            modify_eip_address: modifies the name, description, and maximum bandwidth of an EIP.
            """
            try:
                request = ModifyEipAddressAttributeRequest.ModifyEipAddressAttributeRequest()
                # The ID of the EIP.
                request.set_AllocationId(params['allocation_id'])
                # The maximum bandwidth of the EIP. Unit: Mbit/s.
                request.set_Bandwidth(params['bandwidth'])
                # The name of the EIP.
                request.set_Name(params['name'])
                response = self.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 release_eip_address(self, params):
            """
            release_eip_address: releases the specified EIP.
            """
            try:
                request = ReleaseEipAddressRequest.ReleaseEipAddressRequest()
                # The ID of the EIP to be released.
                request.set_AllocationId(params['allocation_id'])
                response = self.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():
    
        client = AcsClient(
                '<your-access-key-id>',     # Your AccessKey ID.
                '<your-access-key-secret>', # Your AccessKey secret.
                '<your-region-id>')         # Your region ID.
        eip = Eip(client)
        load_balancer = LoadBalancer(client)
        # Create a VPC, create a VSwitch, and then call the ECS API operation to generate an ENI.
        params = {}
        params['vpc_id'] = VPC_ID
        params['vswitch_id'] = VSWITCH_ID
    
        # Create an SLB instance.
        load_balancer_repsonse_json = load_balancer.create_load_balancer(params)
        CommonUtil.log("create_load_balancer", load_balancer_repsonse_json)
    
        # Create an EIP.
        params['load_balancer_id'] = load_balancer_repsonse_json['LoadBalancerId']
        params['instance_id'] = load_balancer_repsonse_json['LoadBalancerId']
        eip_response_json = eip.allocate_eip_address(params)
        CommonUtil.log("allocate_eip_address slb", eip_response_json)
    
        # Associate the EIP with the SLB instance.
        params['allocation_id'] = eip_response_json["AllocationId"]
        params['instance_type'] = 'SlbInstance'
        eip_response_json = eip.associate_eip_address(params)
        CommonUtil.log("associate_eip_address eip", eip_response_json)
    
        # Disassociate the EIP from the SLB instance.
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address slb", eip_response_json)
    
        # Associate the EIP with the ENI.
        params['instance_id'] = ENI_ID
        params['instance_type'] = 'NetworkInterface'
        eip_response_json = eip.associate_eip_address(params)
        CommonUtil.log("associate_eip_address eni", eip_response_json)
    
        # Disassociate the EIP from the ENI.
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address eni", eip_response_json)
    
        # Delete the SLB instance.
        load_balancer_repsonse_json = load_balancer.delete_load_balancer(params)
        CommonUtil.log("delete_load_balancer", load_balancer_repsonse_json)
    
    if __name__ == '__main__':
        sys.exit(main())
  3. Enter the folder where theeip_associate_slb.py file is located, and run the following command to associate an EIP with an SLB instance or ENI.
    Python eip_associate_slb.py

Result

The following output is returned:
---------------------------create_load_balancer---------------------------
{
  "VpcId": "vpc-bp15opprpg0rgxxxxxxxx",
  "AddressIPVersion": "ipv4",
  "LoadBalancerName": "auto_named_slb",
  "ResourceGroupId": "rg-acfm4odxxxxxxxx",
  "VSwitchId": "vsw-bp1e67w26n2sjxxxxxxxx",
  "RequestId": "D3651A96-008C-4B35-A36E-54C2902535C5",
  "Address": "172.xx.xx.146",
  "NetworkType": "vpc",
  "LoadBalancerId": "lb-bp15u6kumammdxxxxxxxx"
}
---------------------------allocate_eip_address slb---------------------------
{
  "EipAddress": "47.xx.xx.76",
  "ResourceGroupId": "rg-acfm4odxxxxxxxx",
  "RequestId": "15FD58CD-B186-4E2C-B4B3-74F712168832",
  "AllocationId": "eip-bp1ofhmmep6rkxxxxxxxx"
}
---------------------------associate_eip_address eip---------------------------
{
  "RequestId": "5EDABF0B-A067-474E-9556-0A3AA870960A"
}
---------------------------unassociate_eip_address slb--------------------------
-
{
  "RequestId": "89556510-D726-490A-9092-9BEA0644CC43"
}
---------------------------associate_eip_address eni---------------------------
{
  "RequestId": "FAE87FDD-232A-4859-803B-F9B57508AEDC"
}
---------------------------unassociate_eip_address eni--------------------------
-
{
  "RequestId": "7DF556E8-12BE-481A-B83D-B3D9E8836534"
}
---------------------------delete_load_balancer---------------------------
{
  "RequestId": "2B70C01A-A440-40A5-A98B-83A687537CCE"
}