本文介绍如何使用Alibaba Cloud SDK for Python创建NAT网关。

前提条件

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

背景信息

本文代码示例中包含以下操作:
  1. 在华东2(上海)地域创建一个VPC。
  2. 在新建的VPC下创建一个vSwitch。
  3. 在新建的VPC下创建一个NAT网关。
  4. 查询新创建的NAT网关。
  5. 删除NAT网关。
  6. 删除vSwitch。
  7. 删除VPC。

操作步骤

  1. 在下载的SDK目录中,打开aliyun-openapi-python-sdk-examples\sdk_examples\examples\natgw文件夹。
  2. 使用编辑器打开natgw_quick_start.py文件,根据实际情况配置相关参数,保存退出。
    完整代码示例如下:
    #encoding=utf-8
    import sys
    import json
    import time
    
    from alibabacloud_credentials.client import Client as CredClient
    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.common_util import CommonUtil
    from sdk_lib.check_status import CheckStatus
    from sdk_lib.exception import ExceptionHandler
    from sdk_lib.consts import *
    
    # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
    # 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
    # 本示例通过阿里云Credentials工具从环境变量中读取AccessKey,来实现API访问的身份验证。如何配置环境变量,请参见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()
    
    # 创建AcsClient实例
    client = AcsClient(access_key_id, access_key_secret, '<your-region-id>')
    
    
    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)
        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-a"
        params['cidr_block'] = "172.16.1.0/24"
        vswitch_json = vswitch.create_vswitch(params)
        CommonUtil.log("create_vswitch", vswitch_json)
    
        # 创建Nat Gateway
        nat_gateway_json = nat_gateway.create_nat_gateway(params)
        CommonUtil.log("create_nat_gateway", nat_gateway_json)
    
        # 查询Nat Gateway
        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)
    
        # 删除Nat Gateway
        nat_gateway_json = nat_gateway.delete_nat_gateway(params)
        CommonUtil.log("delete_nat_gateway", nat_gateway_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_quick_start.py所在的目录,执行如下命令,创建NAT网关。
    python natgw_quick_start.py

执行结果

系统回显结果如下:
---------------------------create_vpc---------------------------
{
  "ResourceGroupId": "rg-acfmxaz****",
  "RouteTableId": "vtb-uf6wzp25d8lkb****",
  "VRouterId": "vrt-uf6di7voecmyq****",
  "VpcId": "vpc-uf63cqupghmk1****",
  "RequestId": "97D36E19-F789-424F-A473-660D63EF8CF9"
}

---------------------------create_vswitch---------------------------
{
  "VSwitchId": "vsw-uf6fovepnk4****",
  "RequestId": "18DA0E81-34A6-4877-9771-E2C4EEEBADD1"
}

---------------------------create_nat_gateway---------------------------
{
  "NatGatewayId": "ngw-uf6mfrcmzktst****",
  "BandwidthPackageIds": {
    "BandwidthPackageId": []
  },
  "ForwardTableIds": {
    "ForwardTableId": [
      "ftb-uf6411str8n9s****"
    ]
  },
  "RequestId": "B1F791C8-73B1-46C5-8A20-726A615BC627",
  "SnatTableIds": {
    "SnatTableId": [
      "stb-uf6t4eijvq3ae****"
    ]
  }
}

---------------------------describe_nat_gateway---------------------------
{
  "TotalCount": 1,
  "PageNumber": 1,
  "RequestId": "1F9303B1-4024-4A92-B67E-FB6BE1DC76D1",
  "PageSize": 10,
  "NatGateways": {
    "NatGateway": [
      {
        "Status": "Available",
        "BandwidthPackageIds": {
          "BandwidthPackageId": []
        },
        "VpcId": "vpc-uf63cqupghmk1****",
        "Description": "",
        "ForwardTableIds": {
          "ForwardTableId": [
            "ftb-uf6411str8n9s****"
          ]
        },
        "IpLists": {
          "IpList": []
        },
        "BusinessStatus": "Normal",
        "RegionId": "cn-shanghai",
        "CreationTime": "2019-04-24T09:09:12Z",
        "NatGatewayId": "ngw-uf6mfrcmzktst****",
        "SnatTableIds": {
          "SnatTableId": [
            "stb-uf6t4eijvq3ae****"
          ]
        },
        "AutoPay": false,
        "InstanceChargeType": "PostPaid",
        "ExpiredTime": "",
        "Spec": "Small",
        "Name": ""
      }
    ]
  }
}

---------------------------delete_nat_gateway---------------------------
{
  "RequestId": "A0B71FE4-4756-4D91-899E-1DFA52D8615E"
}

---------------------------delete_vswitch---------------------------
{
  "RequestId": "F224307E-3DE4-4415-AE19-DDCF24695462"
}

---------------------------delete_vpc---------------------------
{
  "RequestId": "1BFFCBC3-7F83-436C-96E9-CA4A620072DA"
}