すべてのプロダクト
Search
ドキュメントセンター

:DNATエントリの作成

最終更新日:Jan 02, 2024

このトピックでは、Alibaba Cloud SDK for Pythonを使用してDNATエントリを作成する方法について説明します。

前提条件

Alibaba Cloud SDK for Pythonを使用する前に、次の要件が満たされていることを確認してください。
  • Alibaba CloudアカウントとAccessKeyペアが取得されます。 Alibaba Cloud管理コンソールの [セキュリティ管理] ページで、AccessKeyペアを作成して表示できます。
  • Alibaba Cloud SDK for Pythonがインストールされています。
  • VPC Pythonサンプルライブラリがダウンロードされます。
    setup.pyファイルが保存されているディレクトリに移動し、次のコマンドを実行して環境を初期化します。
    python setup.py install

背景情報

このトピックのサンプルコードには、次の操作が含まれます。
  1. 中国 (上海) リージョンに仮想プライベートクラウド (VPC) を作成します。
  2. VPC で vSwitch を作成します。
  3. VPCにNATゲートウェイを作成します。
  4. 中国 (上海) リージョンでelastic IPアドレス (EIP) を作成します。
  5. EIPをNATゲートウェイに関連付けます。
  6. DNATエントリを作成します。
  7. NATゲートウェイに関連付けられているEIPを照会します。
  8. NAT gatewayを照会します。
  9. DNATエントリを削除します。
  10. NATゲートウェイからEIPの関連付けを解除します。
  11. NAT gatewayを削除します。
  12. EIPをリリースします。
  13. vSwitchを削除します。
  14. VPCを削除します。

手順

  1. ダウンロードしたSDKファイルのディレクトリで、aliyun-openapi-python-sdk-examples\sdk_examples\examples\natgwフォルダーを開きます。
  2. テキストエディターでnatgw_snat.pyファイルを開きます。 必要なパラメーターを設定し、設定を保存してから、エディターを終了します。
    次のサンプルコードが表示されます。
    #encoding=utf-8
    インポートsys
    jsonのインポート
    インポート時間
    
    alibabacloud_credentials.clientからCredClientとしてのインポートクライアント
    からaliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    aliyunsdkvpc.request.v20160428からCreateNatGatewayRequestをインポート
    aliyunsdkvpc.request.v20160428からDeleteNatGatewayRequestをインポート
    aliyunsdkvpc.request.v20160428からDescribeNatGatewaysRequestをインポート
    aliyunsdkvpc.request.v20160428からCreateForwardEntryRequestをインポート
    aliyunsdkvpc.request.v20160428からDescribeForwardTableEntriesRequestをインポート
    aliyunsdkvpc.request.v20160428からDeleteForwardEntryRequestをインポート
    sdk_lib.sdk_vpcからVpcをインポート
    sdk_lib.sdk_vswitchからVSwitchをインポート
    sdk_lib.sdk_eipからEipをインポート
    sdk_lib.sdk_cbwpインポートCommonBandwidthPackageから
    sdk_lib.common_utilインポートからCommonUtil
    sdk_lib.check_statusからCheckStatusをインポートする
    sdk_lib.exception import ExceptionHandlerから
    sdk_lib.consts import * から
    
    # Alibaba CloudアカウントのAccessKeyペアを使用すると、アカウントにすべてのAPI操作に対する権限があるため、セキュリティ上のリスクが発生する可能性があります。 RAMユーザーを使用してAPI操作を呼び出したり、ルーチンのO&Mを実行することを推奨します。# AccessKey IDとAccessKey secretをプロジェクトコードに保存することはお勧めしません。 そうしないと、AccessKeyペアが漏洩し、リソースのセキュリティが侵害される可能性があります。 
    # この例では、AccessKeyペアは、Alibaba Cloud Credentialsツールを使用してAPIアクセスを認証することによって取得されます。 変数の設定方法の詳細については、「https://help.aliyun.com/document_detail/378659.htmlhttps:// 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>')
    
    
    クラスNatGateway (オブジェクト):
        def __init__(self, client):
            self.client=クライアント
    
        def create_nat_gateway(self、params):
            """
            create_nat_gateway: NATゲートウェイを作成します。
            """
            試してみてください。
                request = CreateNatGatewayRequest.CreateNatGatewayRequest()
                request.set_VpcId(params['vpc_id'])
                response = client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # NATゲートウェイが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.de scribe_nat_gateway_status,
                                            利用可能、response_json['NatGatewayId']):
                    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ゲートウェイに関する情報を照会します。
            """
            試してみてください。
                request = DescribeNatGatewaysRequest.DescribeNatGatewaysRequest()
                request.set_NatGatewayId(nat_gateway_id)
                response = client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                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ゲートウェイを削除します。
            """
            試してみてください。
                request = DeleteNatGatewayRequest。DeleteNatGatewayRequest()
                request.set_NatGatewayId(params['nat_gateway_id '])
                response = client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # NATゲートウェイが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.de scribe_nat_gateway_status,
                                            ''、params['nat_gateway_id ']):
                    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ゲートウェイのステータスを照会します。
            """
            response = self.de scribe_nat_gateway(nat_gateway_id)
            len(response["NatGateways"]["NatGateway"]) == 0の場合:
                return''
            リターンレスポンス ["NatGateways"]["NatGateway"][0]['Status']
    
        def create_forward_entry(self、params):
            """
            create_forward_entry: DNATエントリを作成します。
            """
            試してみてください。
                request = CreateForwardEntryRequest.CreateForwardEntryRequest()
                request.set_ForwardTableId(params['forward_table_id '])
                request.set_ExternalIp(params['external_ip'])
                request.set_IpProtocol(params['ip_protocol'])
                request.set_ExternalPort(params['external_port'])
                request.set_InternalIp(params['internal_ip'])
                request.set_InternalPort(params['internal_port'])
                response = client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # DNATエントリが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.de scribe_forward_status、
                                            利用可能、params['forward_table_id ']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_forward(self, forward_table_id):
            """
            describe_forward: 指定されたリージョンのDNATエントリに関する情報を照会します。
            """
            試してみてください。
                request = DescribeForwardTableEntriesRequest。DescribeForwardTableEntriesRequest()
                request.set_ForwardTableId(forward_table_id)
                response = client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_forward_status(self, forward_table_id):
            """
            describe_forward_status: 指定されたリージョンのDNATエントリのステータスを照会します。
            """
            response = self.de scribe_forward(forward_table_id)
            if len(response["ForwardTableEntries"]["ForwardTableEntry"]) == 0:
                return''
            リターンレスポンス ["ForwardTableEntries"]["ForwardTableEntry"][0]['Status']
    
        def delete_forward_entry(self、params):
            """
            delete_forward_entry: DNATエントリを削除します。
            """
            試してみてください。
                request = DeleteForwardEntryRequest.DeleteForwardEntryRequest()
                request.set_ForwardTableId(params['forward_table_id '])
                request.set_ForwardEntryId(params['forward_entry_id '])
                response = client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # DNATエントリが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.de scribe_forward_status、
                                            ''、params['forward_table_id ']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
    
    def main():
        vpc = Vpc (クライアント)
        vswitch = VSwitch (クライアント)
        eip = Eip (クライアント)
        cbwp = CommonBandwidthPackage (クライアント)
        nat_gateway = NatGateway (クライアント)
    
        params = {}
    
        # VPCを作成します。
        vpc_json = vpc.create_vpc()
        CommonUtil.log("create_vpc", vpc_json)
    
        # vSwitchを作成します。
        params['vpc_id'] = vpc_json['VpcId']
        params['zone_id'] = "cn-hangzhou-d"
        params['cidr_block'] = "172.16.1.0/24"
        vswitch_json = vswitch.create_vswitch(params)
        CommonUtil.log("create_vswitch", vswitch_json)
        params['vswitch_id'] = vswitch_json['VSwitchId']
    
        # NATゲートウェイを作成します。
        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"]
        params['external_ip'] = eip_response_json['EipAddress']
    
        # 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)
    
        # DNATエントリを作成します。
        params['forward_table_id '] = nat_gateway_json['ForwardTableIds']['ForwardTableId'][0]
        params['ip_protocol'] = 'tcp'
        params['external_port'] = '8080'
        params['internal_port'] = '80'
        params['internal_ip'] = '172.16.1.0'
        forward_entry_json = nat_gateway.create_forward_entry(params)
        CommonUtil.log("create_forward_entry", forward_entry_json)
    
        # EIPを照会します。
        eip_response_json = eip.de scribe_eip_address(params['allocation_id'])
        CommonUtil.log("describe_eip_address", eip_response_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)
    
        # DNATエントリを削除します。
        params['forward_entry_id '] = forward_entry_json['ForwardEntryId']
        forward_entry_json = nat_gateway.delete_forward_entry(params)
        CommonUtil.log("delete_forward_entry", forward_entry_json)
    
        # EIPとNATゲートウェイの関連付けを解除します。
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address nat", eip_response_json)
    
        # NATゲートウェイを削除します。
        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.de lete_vswitch(params)
        CommonUtil.log("delete_vswitch", vswitch_json)
    
        # VPCを削除します。
        vpc_json = vpc.de lete_vpc(params)
        CommonUtil.log("delete_vpc", vpc_json)
    
    
    if __name__ == "__main__":
        sys.exit(main()) 
  3. natgw_snat.pyファイルが保存されているディレクトリに移動し、次のコマンドを実行してDNATエントリを作成します。
    python natgw_dnat.py

結果

次の出力が返されます。
--------------------------- create_vpc ---------------------------
{
  "ResourceGroupId": "rg-acfmxazxxxxxxxx" 、
  "RouteTableId": "vtb-uf63rln6gbb50xxxxxxxx" 、
  "VRouterId": "vrt-uf6p1hfo0ho8gxxxxxxxx" 、
  "VpcId": "vpc-uf6c3r8yca7dhxxxxxxxx" 、
  "RequestId": "1F97FC59-77DF-4D76-BE62-0A13EB4E614C"
}

--------------------------- create_vswitch ---------------------------
{
  "VSwitchId": "vsw-uf6liy66d9ssuxxxxxxxx" 、
  "RequestId": "88CCCFED-1448-49D2-8550-71952981A47A"
}

--------------------------- create_nat_gateway
{
  "NatGatewayId": "ngw-uf6aolgwhssvsxxxxxxxx" 、
  "BandwidthPackageIds": {
    "BandwidthPackageId": []
  },
  "ForwardTableIds": {
    "ForwardTableId": [
      「ftb-uf6unjiun4i12xxxxxxxx」
    ]
  },
  "RequestId": "62A58351-D608-43A4-849E-1E177E917BEA" 、
  "SnatTableIds": {
    "SnatTableId": [
      「stb-uf65utljwcdkpxxxxxxxx」
    ]
  }
}

--------------------------- allocate_eip_address
{
  "EipAddress": "101.xx. xx.110" 、
  "ResourceGroupId": "rg-acfmxazxxxxxxxx" 、
  "RequestId": "0565295E-2F49-4511-93BC-747A2D19A6BD" 、
  "AllocationId": "eip-uf683xrl32ge8xxxxxxxx"
}

--------------------------- associate_eip_address eip ---------------------------
{
  "RequestId": "8759FCE8-F8C2-4372-91D5-7A25D43FD78C"
}

--------------------------- create_forward_entry ---------------------------
{
  "ForwardEntryId": "fwd-uf6ng3wt8sfwmxxxxxxxx" 、
  "RequestId": "CC81BCF6-2F64-40CF-85B0-676A83AC3902"
}

--------------------------- describe_eip_address
{
  &quot;TotalCount&quot;:1、
  "PageNumber":1、
  "PageSize":10、
  "EipAddresses": {
    "EipAddress": [
      {
        "ISP": "BGP" 、
        "ExpiredTime": "",
        "InternetChargeType": "PayByBandwidth",
        "IpAddress": "101.xx. xx.110" 、
        "AllocationId": "eip-uf683xrl32ge8xxxxxxxx" 、
        "PrivateIpAddress": "" 、
        "ステータス": "InUse" 、
        "BandwidthPackageId": "" 、
        "InstanceId": "ngw-uf6aolgwhssvsxxxxxxxx" 、
        "InstanceRegionId": "cn-shanghai" 、
        "RegionId": "cn-shanghai",
        "AvailableRegions": {
          "AvailableRegion": [
            "cn-shanghai"
          ]
        },
        "ResourceGroupId": "rg-acfmxazxxxxxxxx" 、
        "HasReservationData": false、
        "InstanceType": "Nat" 、
        "AllocationTime": "2019-04-24T10:56:53Z" 、
        "名前": "" 、
        "OperationLocks": {
          "LockReason": []
        },
        "モード": "NAT" 、
        "BandwidthPackageType": "" 、
        "BandwidthPackageBandwidth": "" 、
        "Bandwidth": "5",
        "HDMonitorStatus": "OFF" 、
        "ChargeType": "PostPaid" 、
        "SecondLimited": false、
        "Descritpion": "
      }
    ]
  },
  "RequestId": "CD2B3613-2A99-4687-9C23-A8E9F1F03048"
}

--------------------------- describe_nat_gateway
{
  &quot;TotalCount&quot;:1、
  "PageNumber":1、
  "RequestId": "D7519663-8D3B-4CC5-894F-A6798C89688D" 、
  "PageSize":10、
  "NatGateways": {
    "NatGateway": [
      {
        "ステータス": "利用可能" 、
        "BandwidthPackageIds": {
          "BandwidthPackageId": []
        },
        "VpcId": "vpc-uf6c3r8yca7dhxxxxxxxx" 、
        "Description": "",
        "ForwardTableIds": {
          "ForwardTableId": [
            「ftb-uf6unjiun4i12xxxxxxxx」
          ]
        },
        "IpLists": {
          "IpList": [
            {
              "UsingStatus": "UsedByForwardTable" 、
              "IpAddress": "101.xx. xx.110" 、
              "AllocationId": "eip-uf683xrl32ge8xxxxxxxx"
            }
          ]
        },
        "BusinessStatus": "Normal" 、
        "RegionId": "cn-shanghai",
        "CreationTime": "2019-04-24T10:56:50Z" 、
        "NatGatewayId": "ngw-uf6aolgwhssvsxxxxxxxx" 、
        "SnatTableIds": {
          "SnatTableId": [
            「stb-uf65utljwcdkpxxxxxxxx」
          ]
        },
        "AutoPay": false、
        &quot;InstanceChargeType&quot;: &quot;後払い&quot;、
        "ExpiredTime": "",
        "スペック": "小さい" 、
        "名前": ""
      }
    ]
  }
}

--------------------------- delete_forward_entry ---------------------------
{
  "RequestId": "32C76D08-5738-4B07-A638-ACE5F5F5220E"
}

--------------------------- unassociate_eip_address nat --------------------------
-
{
  "RequestId": "AE686920-2CD1-4850-AADC-C249484D4B1A"
}

--------------------------- delete_nat_gateway
{
  "RequestId": "FEBB1E7A-BA5B-4445-B2AB-5B828C17BBE6"
}

--------------------------- release_eip_address
{
  "RequestId": "812D5E78-5113-4B92-892D-0B293BAD66F6"
}

--------------------------- delete_vswitch ---------------------------
{
  "RequestId": "8E13EEE4-21B5-4280-B46B-5C168736DC3A"
}

--------------------------- delete_vpc ---------------------------
{
  "RequestId": "DCBA91E7-F355-4EB6-83E3-27F2E68A8435"
}