This topic describes how to use 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

Before you use Alibaba Cloud SDK for Python, make sure that the following requirements are met:
  • An Alibaba Cloud account and the AccessKey pair are obtained. You can create and view your AccessKey pair on the Security Management page of the Alibaba Cloud Management Console.
  • Alibaba Cloud SDK for Python is installed.
  • The VPC Python example library is downloaded.
    Go to the directory where the setup.py file is stored, and run the following command to initialize the environment:
    python setup.py install

Background information

The sample code in this topic 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 EIP with an ENI.
  6. Disassociate the EIP from the ENI.
  7. Delete the 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 required parameters, save the configurations, and then exit the editor.
    The following sample code is displayed:
    #encoding=utf-8
    import sys
    import json
    from alibabacloud_credentials.client import Client as CredClient
    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
    
    """
    1. Create a VPC. 2. Create a vSwitch. 3. Call the Elastic Compute Service (ECS) API to create 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 ENI. 10. Delete the SLB instance.
    """
    class Eip(object):
        def __init__(self, client):
            self.client = client
    
        def allocate_eip_address(self, params):
            """
            allocate_eip_address: Create 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):
            """
            associate_eip_address: Associate the EIP with a cloud resource 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 resource with which you want to associate the EIP.
                request.set_InstanceType(params['instance_type'])
                # The ID of the cloud resource with which you want to associate the EIP.
                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: Query EIPs in a specific 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: Query the status of an EIP in a 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: Disassociate an EIP from an associated cloud resource.
            """
            try:
                request = UnassociateEipAddressRequest.UnassociateEipAddressRequest()
                # The ID of the EIP.
                request.set_AllocationId(params['allocation_id'])
                # The type of cloud resource from which you want to disassociate the EIP.
                request.set_InstanceType(params['instance_type'])
                # The ID of the cloud resource from which you want to disassociate the EIP.
                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: Modify the name, description, and maximum bandwidth value of the EIP.
            """
            try:
                request = ModifyEipAddressAttributeRequest.ModifyEipAddressAttributeRequest()
                # The ID of the EIP.
                request.set_AllocationId(params['allocation_id'])
                # The maximum bandwidth value 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: Release a specific EIP.
            """
            try:
                request = ReleaseEipAddressRequest.ReleaseEipAddressRequest()
                # The ID of the EIP that you want to release.
                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():
    
        # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        # We do not recommend that you save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of your resources may be compromised. 
        # In this example, the AccessKey pair is obtained by using the Alibaba Cloud Credentials tool to authenticate API access. For more information about how to configure the variables, see https://www.alibabacloud.com/help/alibaba-cloud-sdk-262060/latest/configure-credentials-378659. 
        cred = CredClient()
        access_key_id = cred.get_access_key_id()
        access_key_secret = cred.get_access_key_secret()
    
        # Create an AcsClient instance.
        client = AcsClient(access_key_id, access_key_secret, '<your-region-id>')
    
        eip = Eip(client)
        load_balancer = LoadBalancer(client)
        # Create a VPC, create a vSwitch, and then call the ECS API to create 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 NAT gateway.
        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 NAT gateway.
        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. Go to the directory where the eip_associate_slb.py file is stored, and run the following command to associate the EIP with the SLB instance or the ENI:
    Python eip_associate_slb.py

Result

The following output is returned:
---------------------------create_load_balancer---------------------------
{
  "VpcId": "vpc-bp15opprpg0rg****",
  "AddressIPVersion": "ipv4",
  "LoadBalancerName": "auto_named_slb",
  "ResourceGroupId": "rg-acfm4od****",
  "VSwitchId": "vsw-bp1e67w26n2sj****",
  "RequestId": "D3651A96-008C-4B35-A36E-54C2902535C5",
  "Address": "172.XX.XX.146",
  "NetworkType": "vpc",
  "LoadBalancerId": "lb-bp15u6kumammd****"
}
---------------------------allocate_eip_address slb---------------------------
{
  "EipAddress": "47.XX.XX.76",
  "ResourceGroupId": "rg-acfm4od****",
  "RequestId": "15FD58CD-B186-4E2C-B4B3-74F712168832",
  "AllocationId": "eip-bp1ofhmmep6rk****"
}
---------------------------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"
}