本文介绍如何使用Alibaba Cloud SDK for Python将弹性公网IP绑定到负载均衡实例和弹性网卡。

前提条件

在使用Alibaba Cloud SDK for Python前,您需要完成以下准备工作:
  • 使用Alibaba Cloud SDK for Python,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Python,请参见aliyun-python-sdk-vpc 3.0.8
  • 下载阿里云专有网络Python SDK场景示例的VPC Python Example库
    进入setup.py所在的目录,执行如下命令,完成环境初始化配置。
    python setup.py install

背景信息

本文代码示例中包含以下操作:
  1. 在华东1杭州地域创建负载均衡实例。
  2. 在华东1杭州地域创建EIP。
  3. 将EIP绑定到负载均衡实例。
  4. 将EIP与负载均衡实例解绑。
  5. 将解绑后的EIP绑定到弹性网卡。
  6. 将EIP与弹性网卡解绑。
  7. 删除负载均衡实例。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\eip文件夹。
  2. 使用编辑器打开eip_associate_slb.py文件,根据实际情况配置相关参数,保存退出。
    完整代码示例如下:
    #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
    
    """
    创建VPC->创建VSWITCH->以及调用ECS API生成 ENI(这几步不在以下代码中)
    创建负载均衡->创建EIP->绑定EIP到SLB->解绑EIP->绑定EIP到ENI->解绑EIP->删除负载均衡
    """
    class Eip(object):
        def __init__(self, client):
            self.client = client
    
        def allocate_eip_address(self, params):
            """
            allocate_eip_address: 申请弹性公网IP(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: 将EIP绑定到同地域的云产品实例上
            """
            try:
                request = AssociateEipAddressRequest.AssociateEipAddressRequest()
                # EIP的ID
                request.set_AllocationId(params['allocation_id'])
                # 要绑定的云产品实例的类型
                request.set_InstanceType(params['instance_type'])
                # 要绑定的实例ID
                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: 查询指定地域已创建的EIP。
            """
            try:
                request = DescribeEipAddressesRequest.DescribeEipAddressesRequest()
                # EIP的ID
                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: 查询指定地域已创建的EIP的状态
            """
            # EIP的ID
            response = self.describe_eip_address(allocation_id)
            return response["EipAddresses"]["EipAddress"][0]["Status"]
    
    
        def unassociate_eip_address(self, params):
            """
            unassociate_eip_address: 将EIP从绑定的云资源上解绑。
            """
            try:
                request = UnassociateEipAddressRequest.UnassociateEipAddressRequest()
                # EIP的ID
                request.set_AllocationId(params['allocation_id'])
                # 要解绑的资源类型
                request.set_InstanceType(params['instance_type'])
                # 要解绑的云产品的实例ID
                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: 修改指定EIP的名称、描述信息和带宽峰值
            """
            try:
                request = ModifyEipAddressAttributeRequest.ModifyEipAddressAttributeRequest()
                # 弹性公网IP的ID
                request.set_AllocationId(params['allocation_id'])
                # EIP的带宽峰值,单位为Mbps
                request.set_Bandwidth(params['bandwidth'])
                # 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: 释放指定的EIP。
            """
            try:
                request = ReleaseEipAddressRequest.ReleaseEipAddressRequest()
                # 要释放的弹性公网IP的ID
                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>',     # 您的可用区ID
                '<your-access-key-secret>', # 您的AccessKey ID
                '<your-region-id>')         # 您的AccessKey Secret
        eip = Eip(client)
        load_balancer = LoadBalancer(client)
        #创建VPC, 创建VSWITCH, 以及调用ECS API生成 ENI
        params = {}
        params['vpc_id'] = VPC_ID
        params['vswitch_id'] = VSWITCH_ID
    
        #创建负载均衡
        load_balancer_repsonse_json = load_balancer.create_load_balancer(params)
        CommonUtil.log("create_load_balancer", load_balancer_repsonse_json)
    
        # 创建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)
    
        # 绑定EIP到SLB
        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)
    
        # 解绑EIP
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address slb", eip_response_json)
    
        # 绑定EIP到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)
    
        # 解绑EIP
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address eni", eip_response_json)
    
        # 删除负载均衡实例
        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. 进入eip_associate_slb.py所在的目录,执行如下命令,实现EIP绑定负载均衡实例/弹性网卡。
    Python eip_associate_slb.py

执行结果

系统显示类似如下:
---------------------------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"
}