このトピックでは、Alibaba Cloud SDK for Pythonを使用してEIP (elastic IPアドレス) をNATゲートウェイに関連付け、EIPとNATゲートウェイの関連付けを解除する方法について説明します。
前提条件
Alibaba Cloud SDK for Pythonを使用する前に、次の要件が満たされていることを確認してください。
- Alibaba CloudアカウントとAccessKeyペアが取得されます。 Alibaba Cloud管理コンソールの [セキュリティ管理] ページで、AccessKeyペアを作成して表示できます。
- Alibaba Cloud SDK for Pythonがインストールされています。
- VPC Pythonサンプルライブラリがダウンロードされます。 setup.pyファイルが保存されているディレクトリに移動し、次のコマンドを実行して環境を初期化します。
python setup.py install
手順
- ダウンロードしたSDKファイルのディレクトリで、aliyun-openapi-python-sdk-examples\sdk_examples\examples\natgwフォルダーを開きます。
- テキストエディターでnatgw_associate_eip.pyファイルを開きます。 必要なパラメーターを設定し、設定を保存してから、エディターを終了します。 このトピックのサンプルコードには、次の操作が含まれます。
- 中国 (上海) リージョンに仮想プライベートクラウド (VPC) を作成します。
- VPC で vSwitch を作成します。
- VPCにNATゲートウェイを作成します。
- 中国 (上海) リージョンでEIPを作成します。
- EIPをNATゲートウェイに関連付けます。
- NATゲートウェイに関連付けられているEIPを照会します。
- 中国 (上海) リージョンでEIP帯域幅プランを作成します。
- EIPをEIP帯域幅プランに関連付けます。
- NAT gatewayを照会します。
- NATゲートウェイからEIPの関連付けを解除します。
- EIP帯域幅プランからEIPの関連付けを解除します。
- EIP帯域幅プランを削除します。
- NAT gatewayを削除します。
- EIPをリリースします。
- vSwitchを削除します。
- VPCを削除します。
#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をインポート 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 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-shanghai-d" params['cidr_block'] = "172.16.1.0/24" vswitch_json = vswitch.create_vswitch(params) CommonUtil.log("create_vswitch", vswitch_json) # 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"] # 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.de scribe_eip_address(params['allocation_id']) CommonUtil.log("describe_eip_address", eip_response_json) # EIP帯域幅プランを作成します。 params['bandwidth'] = BANDWIDTH_10 cbwp_repsonse_json = cbwp.create_common_bandwidth_package(params) CommonUtil.log("create_common_bandwidth_package", cbwp_repsonse_json) # EIPを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) # NATゲートウェイを照会します。 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とNATゲートウェイの関連付けを解除します。 eip_response_json = eip.unassociate_eip_address(params) CommonUtil.log("unassociate_eip_address nat", eip_response_json) # EIP帯域幅プランからEIPの関連付けを解除します。 cbwp_repsonse_json = cbwp.remove_common_bandwidth_packageIp(params) CommonUtil.log("remove_common_bandwidth_packageIp", cbwp_repsonse_json) # EIP帯域幅プランを削除します。 params['force'] = True cbwp_repsonse_json = cbwp.de lete_common_bandwidth_package(params) CommonUtil.log("delete_common_bandwidth_package", cbwp_repsonse_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())
- natgw_associate_eip.pyファイルが保存されているディレクトリに移動し、次のコマンドを実行してEIPの関連付けと関連付けを解除します。
python natgw_associate_eip.py
結果
次の出力が返されます。
--------------------------- create_vpc ---------------------------
{
"ResourceGroupId": "rg-acfmxaz ****" 、
"RouteTableId": "vtb-uf6agemvkcmd8 ****" 、
"VRouterId": "vrt-uf6r7lqtsv65d ****" 、
"VpcId": "vpc-uf6mqfqx8vjmo ****" 、
"RequestId": "ADF806C6-FCD6-4E46-B8E3-72C2BE895344"
}
--------------------------- create_vswitch ---------------------------
{
"VSwitchId": "vsw-uf6rm6add6w89 ****" 、
"RequestId": "897FFCC1-E6BA-484E-A245-C5DAEBBA269C"
}
--------------------------- create_nat_gateway
{
"NatGatewayId": "ngw-uf681h38pbvly ****" 、
"BandwidthPackageIds": {
"BandwidthPackageId": []
},
"ForwardTableIds": {
"ForwardTableId": [
"ftb-uf6jd0vbyao2d ****"
]
},
"RequestId": "7C7CD3CB-041A-4B80-80B4-8BF8D5EF0D26" 、
"SnatTableIds": {
"SnatTableId": [
"stb-uf6uj997htg3u ****"
]
}
}
--------------------------- allocate_eip_address
{
"EipAddress": "106.XX. XX.129" 、
"ResourceGroupId": "rg-acfmxaz ****" 、
"RequestId": "DB795B99-1CEA-4FC1-9CE3-9DE2B977BF02" 、
"AllocationId": "eip-uf62tf8y4uyac ****"
}
--------------------------- 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-uf62tf8y4uyac ****" 、
"PrivateIpAddress": "" 、
"ステータス": "InUse" 、
"BandwidthPackageId": "" 、
"InstanceId": "ngw-uf681h38pbvly ****" 、
"InstanceRegionId": "cn-shanghai" 、
"RegionId": "cn-shanghai",
"AvailableRegions": {
"AvailableRegion": [
"cn-shanghai"
]
},
"ResourceGroupId": "rg-acfmxaz ****" 、
"HasReservationData": false、
"InstanceType": "Nat" 、
"AllocationTime": "2019-04-24T10:03:08Z" 、
"名前": "" 、
"OperationLocks": {
"LockReason": []
},
"モード": "NAT" 、
"BandwidthPackageType": "" 、
"BandwidthPackageBandwidth": "" 、
"Bandwidth": "5",
"HDMonitorStatus": "OFF" 、
"ChargeType": "PostPaid" 、
"SecondLimited": false、
"Descritpion": "
}
]
},
"RequestId": "F0AEE605-14AD-4ADD-980C-4B508CE7EE4B"
}
--------------------------- create_common_bandwidth_package ----------------------
-----
{
"ResourceGroupId": "rg-acfmxaz ****" 、
"BandwidthPackageId": "cbwp-uf6dmfvq0gzzg ****" 、
"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": [
{
"ステータス": "利用可能" 、
"BandwidthPackageIds": {
"BandwidthPackageId": []
},
"VpcId": "vpc-uf6mqfqx8vjmo ****" 、
"Description": "",
"ForwardTableIds": {
"ForwardTableId": [
"ftb-uf6jd0vbyao2d ****"
]
},
"IpLists": {
"IpList": [
{
"UsingStatus": "アイドル" 、
"IpAddress": "106.XX. XX.129" 、
"AllocationId": "eip-uf62tf8y4uyac ****"
}
]
},
"BusinessStatus": "Normal" 、
"RegionId": "cn-shanghai",
"CreationTime": "2019-04-24T10:03:05Z" 、
"NatGatewayId": "ngw-uf681h38pbvly ****" 、
"SnatTableIds": {
"SnatTableId": [
"stb-uf6uj997htg3u ****"
]
},
"AutoPay": false、
"InstanceChargeType": "後払い"、
"ExpiredTime": "",
"スペック": "小さい" 、
"名前": ""
}
]
}
}
--------------------------- 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"
}