本文介绍如何使用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杭州地域创建一个EIP。
  2. 在华东1杭州地域创建共享带宽。
  3. 将新创建的EIP加入共享带宽。
  4. 查询共享带宽。
  5. 将EIP移出共享带宽。
  6. 删除共享带宽。
  7. 释放EIP。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\eip文件夹。
  2. 使用编辑器打开eip_add_cbwp.py文件,根据实际情况配置相关参数,保存退出。
    完整代码示例如下:
    #encoding=utf-8
    import sys
    from aliyunsdkvpc.request.v20160428 import CreateCommonBandwidthPackageRequest
    from aliyunsdkvpc.request.v20160428 import AddCommonBandwidthPackageIpRequest
    from aliyunsdkvpc.request.v20160428 import DescribeCommonBandwidthPackagesRequest
    from aliyunsdkvpc.request.v20160428 import RemoveCommonBandwidthPackageIpRequest
    from aliyunsdkvpc.request.v20160428 import DeleteCommonBandwidthPackageRequest
    from sdk_lib.common_util import CommonUtil
    from sdk_lib.sdk_eip import *
    
    """
    创建EIP->创建带宽包->通用带宽包id->添加EIP到共享带宽包中->查询共享带宽包->移除共享带宽包中的EIP->删除共享带宽包->释放EIP
    """
    class CommonBandwidthPackage(object):
        def __init__(self, client):
            self.client = client
    
        def create_common_bandwidth_package(self, params):
            """
            create_common_bandwidth_package: 创建共享带宽
    
            """
            try:
                request = CreateCommonBandwidthPackageRequest.CreateCommonBandwidthPackageRequest()
                # 共享带宽的带宽峰值,单位为Mbps
                request.set_Bandwidth(params['bandwidth'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_cbwp_status,
                                            AVAILABLE, response_json["BandwidthPackageId"]):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def add_common_bandwidth_packageIp(self, params):
            """
            add_common_bandwidth_packageIp: 添加EIP到共享带宽中
    
            """
            try:
                request = AddCommonBandwidthPackageIpRequest.AddCommonBandwidthPackageIpRequest()
                # EIP实例的ID
                request.set_IpInstanceId(params['ip_instance_id'])
                # 共享带宽的ID
                request.set_BandwidthPackageId(params['bandwidth_package_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_cbwp(self, cbwp_id):
            """
            describe_cbwp: 查询共享带宽实例信息
    
            """
            try:
                request = DescribeCommonBandwidthPackagesRequest.DescribeCommonBandwidthPackagesRequest()
                # 共享带宽实例的ID
                request.set_BandwidthPackageId(cbwp_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_cbwp_status(self, cbwp_id):
            """
            describe_cbwp_status: 查询共享带宽实例状态
    
            """
            # 共享带宽实例的ID
            response = self.describe_cbwp(cbwp_id)
            return response["CommonBandwidthPackages"]["CommonBandwidthPackage"][0]["Status"]
    
    
        def remove_common_bandwidth_packageIp(self, params):
            """
            remove_common_bandwidth_packageIp: 移除共享带宽中的EIP
    
            """
            try:
                request = RemoveCommonBandwidthPackageIpRequest.RemoveCommonBandwidthPackageIpRequest()
                # EIP实例的ID
                request.set_IpInstanceId(params['ip_instance_id'])
                # 共享带宽实例的ID
                request.set_BandwidthPackageId(params['bandwidth_package_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 delete_common_bandwidth_package(self, params):
            """
            delete_common_bandwidth_package: 删除共享带宽包
    
            """
            try:
                request = DeleteCommonBandwidthPackageRequest.DeleteCommonBandwidthPackageRequest()
                # 共享带宽实例的ID
                request.set_BandwidthPackageId(params['bandwidth_package_id'])
                # 是否强制删除共享带宽实例
                request.set_Force(params['force'])
                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
    
        params = {}
    
        # 创建EIP
        eip_response_json = eip.allocate_eip_address(params)
        CommonUtil.log("allocate_eip_address", eip_response_json)
        params['allocation_id'] = eip_response_json["AllocationId"]
    
        # 创建带宽包
        params['allocation_id'] = eip_response_json["AllocationId"]
        params['ip_instance_id'] = eip_response_json["AllocationId"]
        params['bandwidth'] = BANDWIDTH_10
        cbwp_repsonse_json = cbwp.create_common_bandwidth_package(params)
        CommonUtil.log("create_common_bandwidth_package", cbwp_repsonse_json)
    
        # 添加EIP到共享带宽包中
        params['bandwidth_package_id'] = cbwp_repsonse_json['BandwidthPackageId']
        cbwp_repsonse_json = cbwp.add_common_bandwidth_packageIp(params)
        CommonUtil.log("add_common_bandwidth_packageIp", cbwp_repsonse_json)
    
        # 查询共享带宽包
        cbwp_repsonse_json = cbwp.describe_cbwp(params['bandwidth_package_id'])
        CommonUtil.log("add_common_bandwidth_packageIp", cbwp_repsonse_json)
    
        # 移除共享带宽包中的EIP(
        cbwp_repsonse_json = cbwp.remove_common_bandwidth_packageIp(params)
        CommonUtil.log("remove_common_bandwidth_packageIp", cbwp_repsonse_json)
    
        # 删除共享带宽包
        params['force'] = True
        cbwp_repsonse_json = cbwp.delete_common_bandwidth_package(params)
        CommonUtil.log("delete_common_bandwidth_package", cbwp_repsonse_json)
    
        # 释放EIP
        eip_response_json = eip.release_eip_address(params)
        CommonUtil.log("release_eip_address", eip_response_json)
    
    if __name__ == '__main__':
        sys.exit(main())
  3. 进入eip_add_cbwp.py所在的目录,执行如下命令,实现EIP加入共享带宽。
    python eip_add_cbwp.py

执行结果

系统显示类似如下:
---------------------------allocate_eip_address---------------------------
{
  "EipAddress": "118.xx.xx.198",
  "ResourceGroupId": "rg-acfm4odxxxxxxxx",
  "RequestId": "A830A607-B7C4-49FE-A6EE-7237D64CDE2D",
  "AllocationId": "eip-bp1mdyvr22qvgxxxxxxxx"
}
---------------------------create_common_bandwidth_package----------------------
-----
{
  "ResourceGroupId": "rg-acfm4odxxxxxxxx",
  "BandwidthPackageId": "cbwp-bp12k058pjjiexxxxxxxx",
  "RequestId": "93127320-DD79-4F83-A3B9-DC99D0597B0C"
}
---------------------------add_common_bandwidth_packageIp-----------------------
----
{
  "RequestId": "7F314AFE-B398-4348-AF61-B7D27B731286"
}
---------------------------add_common_bandwidth_packageIp-----------------------
----
{
  "TotalCount": 1,
  "CommonBandwidthPackages": {
    "CommonBandwidthPackage": [
      {
        "Status": "Available",
        "PublicIpAddresses": {
          "PublicIpAddresse": [
            {
              "IpAddress": "118.xx.xx.198",
              "AllocationId": "eip-bp1mdyvr22qvgxxxxxxxx"
            }
          ]
        },
        "BusinessStatus": "Normal",
        "RegionId": "cn-hangzhou",
        "BandwidthPackageId": "cbwp-bp12k058pjjiexxxxxxxx",
        "Name": "",
        "ISP": "BGP",
        "CreationTime": "2019-04-18T01:46:17Z",
        "ResourceGroupId": "rg-acfm4odxxxxxxxx",
        "Bandwidth": "10",
        "InstanceChargeType": "PostPaid",
        "HasReservationData": false,
        "InternetChargeType": "PayByBandwidth",
        "ExpiredTime": "",
        "Ratio": 100,
        "Description": ""
      }
    ]
  },
  "PageNumber": 1,
  "RequestId": "015DD0FA-742B-4431-92EA-E3F03FDEB8CD",
  "PageSize": 10
}
---------------------------remove_common_bandwidth_packageIp--------------------
-------
{
  "RequestId": "A49C9126-B703-4D34-B552-A7FE283FB5DD"
}
---------------------------delete_common_bandwidth_package----------------------
-----
{
  "RequestId": "E423F648-C169-4B63-A2CF-5E6C8E441DE1"
}
---------------------------release_eip_address---------------------------
{
  "RequestId": "7E0D34AE-58C3-468A-B021-378F8938AE6B"
}