本文介绍如何使用Alibaba Cloud SDK for Python从NAT网关上绑定或解绑一个弹性公网IP(EIP)。

前提条件

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

背景信息

本文代码示例中包含以下操作:
  1. 在华东2上海地域创建一个VPC。
  2. 在新建的VPC下创建一个VSwitch。
  3. 在新建的VPC下创建一个NAT网关。
  4. 在华东2上海地域创建一个EIP。
  5. 将创建的EIP绑定到NAT网关。
  6. 查询绑定到NAT网关的EIP。
  7. 在华东2上海地域创建共享带宽实例。
  8. 添加EIP到共享带宽实例。
  9. 查询已创建的NAT网关。
  10. 将EIP与NAT网关解绑。
  11. 将EIP从共享带宽实例中移出。
  12. 删除共享带宽实例。
  13. 删除NAT网关。
  14. 释放EIP。
  15. 删除VSwitch。
  16. 删除VPC。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\natgw文件夹。
  2. 使用编辑器打开natgw_associate_eip.py文件,根据实际情况配置相关参数,保存退出。
    完整代码示例如下:
    #encoding=utf-8
    import sys
    import json
    import time
    
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    from aliyunsdkvpc.request.v20160428 import CreateNatGatewayRequest
    from aliyunsdkvpc.request.v20160428 import DeleteNatGatewayRequest
    from aliyunsdkvpc.request.v20160428 import DescribeNatGatewaysRequest
    from sdk_lib.sdk_vpc import Vpc
    from sdk_lib.sdk_vswitch import VSwitch
    from sdk_lib.sdk_eip import Eip
    from sdk_lib.sdk_cbwp import CommonBandwidthPackage
    from sdk_lib.common_util import CommonUtil
    from sdk_lib.check_status import CheckStatus
    from sdk_lib.exception import ExceptionHandler
    from sdk_lib.consts import *
    
    client = AcsClient(
        'accessKeyId',
        'accessSecret',
        'RegionId'
        #timeout = 35
    )
    
    
    class NatGateway(object):
        def __init__(self, client):
            self.client = client
    
        def create_nat_gateway(self, params):
            """
            create_nat_gateway: 创建nat gateway
            """
            try:
                request = CreateNatGatewayRequest.CreateNatGatewayRequest()
                request.set_VpcId(params['vpc_id'])
                response = client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断Nat Gateway状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_nat_gateway_status,
                                            AVAILABLE, response_json['NatGatewayId']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_nat_gateway(self, nat_gateway_id):
            """
            describe_nat_gateway: 查询指定地域已创建的nat gateway的信息
            """
            try:
                request = DescribeNatGatewaysRequest.DescribeNatGatewaysRequest()
                request.set_NatGatewayId(nat_gateway_id)
                response = 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_nat_gateway(self, params):
            """
            delete_nat_gateway: 删除nat gateway
            """
            try:
                request = DeleteNatGatewayRequest.DeleteNatGatewayRequest()
                request.set_NatGatewayId(params['nat_gateway_id'])
                response = client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断Nat Gateway状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.describe_nat_gateway_status,
                                            '', params['nat_gateway_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_nat_gateway_status(self, nat_gateway_id):
            """
            describe_nat_gateway_status: 查询指定地域已创建的nat gateway的状态
            """
            response = self.describe_nat_gateway(nat_gateway_id)
            if len(response["NatGateways"]["NatGateway"]) == 0:
                return ''
            return response["NatGateways"]["NatGateway"][0]['Status']
    
    
    def main():
        vpc = Vpc(client)
        vswitch = VSwitch(client)
        eip = Eip(client)
        cbwp = CommonBandwidthPackage(client)
        nat_gateway = NatGateway(client)
    
        params = {}
    
        # 创建vpc
        vpc_json = vpc.create_vpc()
        CommonUtil.log("create_vpc", vpc_json)
    
        # 创建vswitch
        params['vpc_id'] = vpc_json['VpcId']
        params['zone_id'] = "cn-shanghai-d"
        params['cidr_block'] = "172.16.1.0/24"
        vswitch_json = vswitch.create_vswitch(params)
        CommonUtil.log("create_vswitch", vswitch_json)
    
        # 创建natgw
        nat_gateway_json = nat_gateway.create_nat_gateway(params)
        CommonUtil.log("create_nat_gateway", nat_gateway_json)
    
        # 创建EIP
        eip_response_json = eip.allocate_eip_address(params)
        CommonUtil.log("allocate_eip_address", eip_response_json)
        params['allocation_id'] = eip_response_json["AllocationId"]
    
        # 绑定EIP到NAT网关
        params['instance_id'] = nat_gateway_json['NatGatewayId']
        params['allocation_id'] = eip_response_json["AllocationId"]
        params['instance_type'] = 'Nat'
        eip_response_json = eip.associate_eip_address(params)
        CommonUtil.log("associate_eip_address eip", eip_response_json)
    
        # 查询EIP
        eip_response_json = eip.describe_eip_address(params['allocation_id'])
        CommonUtil.log("describe_eip_address", eip_response_json)
    
        # 创建带宽包
        params['bandwidth'] = BANDWIDTH_10
        cbwp_repsonse_json = cbwp.create_common_bandwidth_package(params)
        CommonUtil.log("create_common_bandwidth_package", cbwp_repsonse_json)
    
        # 添加EIP到共享带宽包中
        params['ip_instance_id'] = params['allocation_id']
        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)
    
        # 查询natgw
        params['nat_gateway_id'] = nat_gateway_json['NatGatewayId']
        nat_gateway_json = nat_gateway.describe_nat_gateway(params['nat_gateway_id'])
        CommonUtil.log("describe_nat_gateway", nat_gateway_json)
    
        # 解绑EIP
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address nat", eip_response_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)
    
        # 删除natgw
        nat_gateway_json = nat_gateway.delete_nat_gateway(params)
        CommonUtil.log("delete_nat_gateway", nat_gateway_json)
    
        # 释放EIP
        eip_response_json = eip.release_eip_address(params)
        CommonUtil.log("release_eip_address", eip_response_json)
    
        # 删除vswitch
        params['vswitch_id'] = vswitch_json['VSwitchId']
        vswitch_json = vswitch.delete_vswitch(params)
        CommonUtil.log("delete_vswitch", vswitch_json)
    
        # 删除vpc
        vpc_json = vpc.delete_vpc(params)
        CommonUtil.log("delete_vpc", vpc_json)
    
    
    if __name__ == "__main__":
        sys.exit(main())
  3. 进入natgw_associate_eip.py所在的目录,执行如下命令,绑定和解绑EIP。
    python natgw_associate_eip.py

执行结果

系统显示类似如下:
---------------------------create_vpc---------------------------
{
  "ResourceGroupId": "rg-acfmxazxxxxxxxx",
  "RouteTableId": "vtb-uf6agemvkcmd8xxxxxxxx",
  "VRouterId": "vrt-uf6r7lqtsv65dxxxxxxxx",
  "VpcId": "vpc-uf6mqfqx8vjmoxxxxxxxx",
  "RequestId": "ADF806C6-FCD6-4E46-B8E3-72C2BE895344"
}

---------------------------create_vswitch---------------------------
{
  "VSwitchId": "vsw-uf6rm6add6w89xxxxxxxx",
  "RequestId": "897FFCC1-E6BA-484E-A245-C5DAEBBA269C"
}

---------------------------create_nat_gateway---------------------------
{
  "NatGatewayId": "ngw-uf681h38pbvlyxxxxxxxx",
  "BandwidthPackageIds": {
    "BandwidthPackageId": []
  },
  "ForwardTableIds": {
    "ForwardTableId": [
      "ftb-uf6jd0vbyao2dxxxxxxxx"
    ]
  },
  "RequestId": "7C7CD3CB-041A-4B80-80B4-8BF8D5EF0D26",
  "SnatTableIds": {
    "SnatTableId": [
      "stb-uf6uj997htg3uxxxxxxxx"
    ]
  }
}

---------------------------allocate_eip_address---------------------------
{
  "EipAddress": "106.xx.xx.129",
  "ResourceGroupId": "rg-acfmxazxxxxxxxx",
  "RequestId": "DB795B99-1CEA-4FC1-9CE3-9DE2B977BF02",
  "AllocationId": "eip-uf62tf8y4uyacxxxxxxxx"
}

---------------------------associate_eip_address eip---------------------------
{
  "RequestId": "443D7060-B716-4193-A44D-23FE762004F8"
}

---------------------------describe_eip_address---------------------------
{
  "TotalCount": 1,
  "PageNumber": 1,
  "PageSize": 10,
  "EipAddresses": {
    "EipAddress": [
      {
        "ISP": "BGP",
        "ExpiredTime": "",
        "InternetChargeType": "PayByBandwidth",
        "IpAddress": "106.xx.xx.129",
        "AllocationId": "eip-uf62tf8y4uyacxxxxxxxx",
        "PrivateIpAddress": "",
        "Status": "InUse",
        "BandwidthPackageId": "",
        "InstanceId": "ngw-uf681h38pbvlyxxxxxxxx",
        "InstanceRegionId": "cn-shanghai",
        "RegionId": "cn-shanghai",
        "AvailableRegions": {
          "AvailableRegion": [
            "cn-shanghai"
          ]
        },
        "ResourceGroupId": "rg-acfmxazxxxxxxxx",
        "HasReservationData": false,
        "InstanceType": "Nat",
        "AllocationTime": "2019-04-24T10:03:08Z",
        "Name": "",
        "OperationLocks": {
          "LockReason": []
        },
        "Mode": "NAT",
        "BandwidthPackageType": "",
        "BandwidthPackageBandwidth": "",
        "Bandwidth": "5",
        "HDMonitorStatus": "OFF",
        "ChargeType": "PostPaid",
        "SecondLimited": false,
        "Descritpion": ""
      }
    ]
  },
  "RequestId": "F0AEE605-14AD-4ADD-980C-4B508CE7EE4B"
}

---------------------------create_common_bandwidth_package----------------------
-----
{
  "ResourceGroupId": "rg-acfmxazxxxxxxxx",
  "BandwidthPackageId": "cbwp-uf6dmfvq0gzzgxxxxxxxx",
  "RequestId": "D5E02777-2A72-42EC-8308-5D4B6E56D900"
}

---------------------------add_common_bandwidth_packageIp-----------------------
----
{
  "RequestId": "3B4CD99C-6E59-4DA2-9256-EACF3F699412"
}

---------------------------describe_nat_gateway---------------------------
{
  "TotalCount": 1,
  "PageNumber": 1,
  "RequestId": "A07498A0-4D60-4E0F-A7DE-3A832B174D59",
  "PageSize": 10,
  "NatGateways": {
    "NatGateway": [
      {
        "Status": "Available",
        "BandwidthPackageIds": {
          "BandwidthPackageId": []
        },
        "VpcId": "vpc-uf6mqfqx8vjmoxxxxxxxx",
        "Description": "",
        "ForwardTableIds": {
          "ForwardTableId": [
            "ftb-uf6jd0vbyao2dxxxxxxxx"
          ]
        },
        "IpLists": {
          "IpList": [
            {
              "UsingStatus": "Idle",
              "IpAddress": "106.xx.xx.129",
              "AllocationId": "eip-uf62tf8y4uyacxxxxxxxx"
            }
          ]
        },
        "BusinessStatus": "Normal",
        "RegionId": "cn-shanghai",
        "CreationTime": "2019-04-24T10:03:05Z",
        "NatGatewayId": "ngw-uf681h38pbvlyxxxxxxxx",
        "SnatTableIds": {
          "SnatTableId": [
            "stb-uf6uj997htg3uxxxxxxxx"
          ]
        },
        "AutoPay": false,
        "InstanceChargeType": "PostPaid",
        "ExpiredTime": "",
        "Spec": "Small",
        "Name": ""
      }
    ]
  }
}

---------------------------unassociate_eip_address nat--------------------------
-
{
  "RequestId": "92CB670E-239D-4659-B91F-E0565D5C0F2D"
}

---------------------------remove_common_bandwidth_packageIp--------------------
-------
{
  "RequestId": "A58E9647-6761-4CA3-8786-3CD4E7D2A7AB"
}

---------------------------delete_common_bandwidth_package----------------------
-----
{
  "RequestId": "4AA428BC-B72F-4567-94B8-AC2398EF7529"
}

---------------------------delete_nat_gateway---------------------------
{
  "RequestId": "EC6C5D04-AF7D-4560-A30E-80EC141D174D"
}

---------------------------release_eip_address---------------------------
{
  "RequestId": "9B1380B3-EE97-49BD-88FE-DBF356304208"
}

---------------------------delete_vswitch---------------------------
{
  "RequestId": "A9A1D63E-5709-4B98-90BF-9069AA264230"
}

---------------------------delete_vpc---------------------------
{
  "RequestId": "3B687C37-5315-4E0B-BE13-103BB287A80D"
}