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

:同じリージョンとAlibaba Cloudアカウントに属する2つのVPCを接続する

最終更新日:Jan 02, 2024

このトピックでは、Alibaba Cloud SDK for Pythonを使用して、同じリージョンとAlibaba Cloudアカウントに属する2つの仮想プライベートクラウド (VPC) を接続する方法について説明します。

前提条件

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

背景情報

ルーターインターフェイスを作成するときは、次の制限に注意してください。
  • 2つのルーター間に接続するインターフェイスのペアを1つだけ作成できます。
  • 各ルーターに最大5つのインターフェイスを作成できます。
  • Alibaba Cloudアカウントに料金滞納のルーターインターフェイスがある場合、新しいルーターインターフェイスを作成することはできません。
  • 同じルートテーブル内のルートエントリの各宛先CIDRブロックは一意である必要があります。

手順

  1. ダウンロードしたSDKファイルのディレクトリで、aliyun-openapi-python-sdk-examples\sdk_examples\examples\ecフォルダーを開きます。
  2. テキストエディターでec_same_account.pyファイルを開きます。 必要なパラメーターを設定し、設定を保存してから、エディターを終了します。
    このトピックのコードサンプルには、次の操作が含まれます。
    1. 開始側ルーターのインターフェイスを作成します。
    2. レシーバールーターのインターフェイスを作成します。
    3. 開始側ルーターインターフェイスの設定を変更します。
    4. レシーバールーターインターフェイスの設定を変更します。
    5. 開始側ルーターインターフェイスに関する情報を照会します。
    6. 受信機ルーターインターフェイスに関する情報を照会します。
    7. 開始側ルーターインターフェイスを受信側ルーターインターフェイスに接続します。
    8. 次のホップが開始側ルーターインターフェイスであるルートを作成します。
    9. 次のホップがレシーバールーターインターフェイスであるルートを作成します。
    10. 次のホップがレシーバールーターインターフェイスであるルートを削除します。
    11. 次のホップが開始側ルーターインターフェイスであるルートを削除します。
    12. 開始側ルーターインターフェイスを無効にします。
    13. レシーバールーターインターフェイスを無効にします。
    14. 開始側ルーターインターフェイスを削除します。
    15. レシーバールーターインターフェイスを削除します。
    #encoding=utf-8
    インポートsys
    jsonのインポート
    alibabacloud_credentials.clientからCredClientとしてのインポートクライアント
    からaliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    aliyunsdkvpc.request.v20160428からCreateRouterInterfaceRequestをインポート
    aliyunsdkvpc.request.v20160428からDeleteRouterInterfaceRequestをインポート
    aliyunsdkvpc.request.v20160428からDescribeRouterInterfacesRequestをインポート
    aliyunsdkvpc.request.v20160428からConnectRouterInterfaceRequestをインポート
    aliyunsdkvpc.request.v20160428からDeactivateRouterInterfaceRequestをインポート
    aliyunsdkvpc.request.v20160428からModifyRouterInterfaceAttributeRequestをインポートする
    sdk_lib.sdk_route_entryからRouteEntryをインポートする
    sdk_lib.exception import ExceptionHandlerから
    sdk_lib.common_utilインポートからCommonUtil
    sdk_lib.check_statusからCheckStatusをインポートする
    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>')
    
    クラスRouterInterface (オブジェクト):
        def __init__(self, client):
            self.client=クライアント
    
        def create_router_interface(self、params):
            """
            create_router_interface: ルーターインターフェイスを作成します。
            """
            試してみてください。
                request = CreateRouterInterfaceRequest.CreateRouterInterfaceRequest()
                # ルーターインターフェイスの仕様。
                request.set_Spec(params['spec'])
                # ルーターインターフェイスの役割。
                request.set_Role(params['role'])
                # ルーターインターフェイスに関連付けられているルーターのID。
                request.set_RouterId(params['router_id'])
                # ルーターインターフェイスに関連付けられているルーターのタイプ。
                request.set_RouterType(params['router_type'])
                # レシーバーがデプロイされているリージョンのID。
                request.set_OppositeRegionId(params['opposite_region_id '])
                # ピアルーターインターフェイスに関連付けられているルーターのタイプ。
                request.set_OppositeRouterType(params['opposite_router_type '])
    
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # ルーターインターフェイスが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.de scribe_ri_status,
                                            'Idle' 、response_json['RouterInterfaceId']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def connect_router_interface(self、params):
            """
            connect_router_interface: 接続要求が開始側ルーターインターフェイスから受信側ルーターインターフェイスに送信されます。
            """
            試してみてください。
                request = ConnectRouterInterfaceRequest.ConnectRouterInterfaceRequest()
                # 接続要求を開始する開始側ルーターインターフェイスのID。
                request.set_RouterInterfaceId(params['router_interface_id '])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                CheckStatus.check_status(TIME_DEFAULT_OUT * 5、DEFAULT_TIME * 5、
                                            self.de scribe_ri_status,
                                            'Active' 、params['router_interface_id ']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def deactivate_router_interface(self、params):
            """
            deactivate_router_interface: ルーターインターフェイスを無効にします。
            """
            試してみてください。
                request = DeactivateRouterInterfaceRequest。DeactivateRouterInterfaceRequest()
                # ルーターインターフェイスのID。
                request.set_RouterInterfaceId(params['router_interface_id '])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # ルーターインターフェイスが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT * 5、DEFAULT_TIME * 5、
                                            self.de scribe_ri_status,
                                            'Inactive '、params['router_interface_id']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def modify_router_interface_attribute(self, params):
            """
            modify_router_interface_attribute: ルーターインターフェイスの設定を変更します。
            """
            試してみてください。
                request = ModifyRouterInterfaceAttributeRequest。ModifyRouterInterfaceAttributeRequest()
                # ルーターインターフェイスのID。
                request.set_RouterInterfaceId(params['router_interface_id '])
                # ピアルーターインターフェイスのID。
                request.set_OppositeInterfaceId(params['opposite_interface_id '])
                # ピアルーターのID。
                request.set_OppositeRouterId(params['opposite_router_id '])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # ルーターインターフェイスが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.de scribe_ri_status,
                                            'Idle' 、params['router_interface_id ']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
    
    
        def describe_router_interface(self, instance_id):
            """
            describe_router_interface: 特定のリージョンのルーターインターフェイスを照会します。
            """
            試してみてください。
                request = DescribeRouterInterfacesRequest.DescribeRouterInterfacesRequest()
                # ルーターインターフェイスのクエリに使用されるフィルター条件の種類。
                request.add_query_param('Filter.1.Key' 、"RouterInterfaceId")
                # 照会するルーターインターフェイスのID。
                request.add_query_param('Filter.1.Value.1 '、instance_id)
                response = self.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_ri_status(self, instance_id):
            """
            describe_ri_status: 特定のリージョンのルーターインターフェイスの状態を照会します。
            """
            response = self.de scribe_router_interface(instance_id)
            if len(response['RouterInterfaceSet']['RouterInterfaceType']) == 0:
                return''
            リターンレスポンス ['RouterInterfaceSet']['RouterInterfaceType'][0]['Status']
    
        def delete_router_interface(self、params):
            """
            delete_router_interface: ルーターインターフェイスを削除します。
            """
            試してみてください。
                request = DeleteRouterInterfaceRequest。DeleteRouterInterfaceRequest()
                # ルーターインターフェイスのID。
                request.set_RouterInterfaceId(params['instance_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                # ルーターインターフェイスが使用可能状態かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.de scribe_ri_status,
                                            ''、params['instance_id']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
    def main():
        client = ACS_CLIENT
        router_interface = RouterInterface (クライアント)
        route_entry = RouteEntry (クライアント)
    
        params = {}
        params['spec'] = "Large.2"
        params['role'] = "InitiatingSide"
        params['router_id'] = ROUTER_ID
        params['router_type'] = "VRouter"
        params['opposite_region_id '] = "cn-hangzhou"
        params['opposite_router_type '] = "VRouter"
    
        # イニシエータルーターインターフェイスを作成します。
        router_interface_json = router_interface.create_router_interface(params)
        CommonUtil.log("create_router_interface", router_interface_json)
    
        # レシーバールーターインターフェイスを作成します。
        params['spec'] = "Negative"
        params['role'] = "AcceptingSide"
        params['router_id'] = ROUTER_ID2
        router_interface_json2 = router_interface.create_router_interface(params)
        CommonUtil.log("create_router_interface", router_interface_json2)
    
        # イニシエータルーターインターフェイスに関する情報を変更します。
        params['router_interface_id '] = router_interface_json['RouterInterfaceId']
        params['opposite_interface_id '] = router_interface_json2['RouterInterfaceId']
        params['opposite_router_id '] = ROUTER_ID2
        modify_ri_json = router_interface.modify_router_interface_attribute(params)
        CommonUtil.log("modify_router_interface_attribute", modify_ri_json)
    
        # レシーバールーターインターフェイスに関する情報を変更します。
        params['router_interface_id '] = router_interface_json2['RouterInterfaceId']
        params['opposite_interface_id '] = router_interface_json['RouterInterfaceId']
        params['opposite_router_id '] = ROUTER_ID
        modify_ri_json2 = router_interface.modify_router_interface_attribute(params)
        CommonUtil.log("modify_router_interface_attribute", modify_ri_json2)
    
        # 開始側ルーターインターフェイスに関する情報を照会します。
        describe_ri_json = router_interface.describe_router_interface(router_interface_json['RouterInterfaceId'])
        CommonUtil.log("describe_router_interface", describe_ri_json)
    
        # レシーバールーターインターフェイスに関する情報を照会します。
        describe_ri_json2 = router_interface.describe_router_interface(router_interface_json2['RouterInterfaceId'])
        CommonUtil.log("describe_router_interface", describe_ri_json2)
    
        # 接続を開始します。
        params['router_interface_id '] = router_interface_json['RouterInterfaceId']
        connect_ri_json = router_interface.connect_router_interface(params)
        CommonUtil.log("connect_router_interface", connect_ri_json)
    
        # 次のホップが開始側ルーターインターフェイスであるルートを作成します。
        params ['rout_table_id '] =table_id
        params ['_destination cidr_block '] = "0.0.0.0/0"
        params['nexthop_type'] = 'RouterInterface'
        params['nexthop_id'] = router_interface_json['RouterInterfaceId']
        route_entry_json = route_entry.create_route_entry(params)
        CommonUtil.log("create_route_entry", route_entry_json)
    
        # ネクストホップがレシーバールーターインターフェイスであるルートを作成します。
        params ['rout_table_id '] = TABLE_ID2
        params ['_destination cidr_block '] = "0.0.0.0/0"
        params['nexthop_type'] = 'RouterInterface'
        params['nexthop_id'] = router_interface_json2['RouterInterfaceId']
        route_entry_json2 = route_entry.create_route_entry(params)
        CommonUtil.log("create_route_entry", route_entry_json2)
    
        # ネクストホップがレシーバールーターインターフェイスであるルートを削除します。
        route_entry_json = route_entry.delete_route_entry(params)
        CommonUtil.log("delete_route_entry", route_entry_json)
    
        # 次のホップが開始側ルーターインターフェイスであるルートを削除します。
        params ['rout_table_id '] =table_id
        params['nexthop_id'] = router_interface_json['RouterInterfaceId']
        route_entry_json = route_entry.delete_route_entry(params)
        CommonUtil.log("delete_route_entry", route_entry_json)
    
        # 開始側ルーターインターフェイスを無効にします。
        params['router_interface_id '] = router_interface_json['RouterInterfaceId']
        deactivate_ri_json = router_interface.deactivate_router_interface(params)
        CommonUtil.log("deactivate_router_interface", deactivate_ri_json)
    
        # レシーバールーターインターフェイスを無効にします。
        params['router_interface_id '] = router_interface_json2['RouterInterfaceId']
        deactivate_ri_json2 = router_interface.deactivate_router_interface(params)
        CommonUtil.log("deactivate_router_interface", deactivate_ri_json2)
    
        # イニシエータルーターインターフェイスを削除します。
        params['instance_id'] = router_interface_json['RouterInterfaceId']
        router_interface_json = router_interface.delete_router_interface(params)
        CommonUtil.log("delete_router_interface", router_interface_json)
    
        # レシーバールーターインターフェイスを削除します。
        params['instance_id'] = router_interface_json2['RouterInterfaceId']
        router_interface_json2 = router_interface.delete_router_interface(params)
        CommonUtil.log("delete_router_interface", router_interface_json2)
    
    
    if __name__ ='__main__':
        sys.exit(main())
                            
  3. ec_same_account.pyファイルが保存されているディレクトリに移動し、次のコマンドを実行して、同じリージョンとAlibaba Cloudアカウントに属する2つのVPCを接続します。
    python ec_same_account.py

結果

次の出力が返されます。
--------------------------- create_router_interface ---------------------------
{
  "RequestId": "F5493DC1-53B0-4916-874F-87773A54525F" 、 
  "RouterInterfaceId": "ri-bp1ujwb6xsw16 ****"
}
--------------------------- create_router_interface ---------------------------
{
  "RequestId": "E3F5BE99-B2C5-4751-8173-0F590300EE72" 、 
  "RouterInterfaceId": "ri-bp1vze2rusg2c ****"
}
--------------------------- modify_router_interface_attribute ---------------------------
{
  "RequestId": "8D691507-F31A-41E5-9C72-457EFF1F7727"
}
--------------------------- modify_router_interface_attribute ---------------------------
{
  "RequestId": "2E664208-8F37-4F19-B719-00B4F1AF03B2"
}
--------------------------- describe_router_interface ---------------------------
{
  &quot;TotalCount&quot;:1、 
  "RouterInterfaceSet": {
    "RouterInterfaceType": [
      {
        "BusinessStatus": "Normal" 、 
        "CreationTime": "2019-04-30T06:09:16Z" 、 
        "ロール": "InitiatingSide" 、 
        "OppositeRouterId": "vrt-bp141no9pds2b ****" 、 
        "スペック": "Large.2" 、 
        "ステータス": "アイドル" 、 
        "EndTime": "2999-09-08T16:00:00Z" 、 
        "OppositeInterfaceSpec": "ネガティブ" 、 
        "RouterInterfaceId": "ri-bp1ujwb6xsw16 ****" 、 
        "RouterType": "VRouter" 、 
        "OppositeBandwidth": 0、 
        "OppositeVpcInstanceId": "vpc-bp1v31by9jix2 ****" 、 
        "HasReservationData": false、 
        "OppositeInterfaceBusinessStatus": "通常" 、 
        "OppositeRouterType": "VRouter" 、 
        "OppositeRegionId": "cn-hangzhou" 、 
        "VpcInstanceId": "vpc-bp15opprpg0rg ****" 、 
        "RouterId": "vrt-bp1ltkytn6lgm ****" 、 
        "CrossBorder": false、 
        "OppositeInterfaceOwnerId": "" 、 
        "帯域幅": 2048、 
        "OppositeInterfaceId": "ri-bp1vze2rusg2c ****" 、 
        "ChargeType": "AfterPay"
      }
    ]
  }, 
  "PageNumber":1、 
  "RequestId": "89EF0631-0A36-41AD-A586-AF4FFDA6E68B" 、 
  "PageSize": 10
}
--------------------------- describe_router_interface ---------------------------
{
  &quot;TotalCount&quot;:1、 
  "RouterInterfaceSet": {
    "RouterInterfaceType": [
      {
        "ステータス": "アイドル" 、 
        "OppositeRegionId": "cn-hangzhou" 、 
        "BusinessStatus": "Normal" 、 
        "OppositeRouterId": "vrt-bp1ltkytn6lgm ****" 、 
        "VpcInstanceId": "vpc-bp1v31by9jix2 ****" 、 
        "RouterInterfaceId": "ri-bp1vze2rusg2c ****" 、 
        "CreationTime": "2019-04-30T06:09:18Z" 、 
        "RouterType": "VRouter" 、 
        "OppositeInterfaceOwnerId": "" 、 
        "RouterId": "vrt-bp141no9pds2b ****" 、 
        "帯域幅": 0、 
        "OppositeInterfaceId": "ri-bp1ujwb6xsw16 ****" 、 
        "EndTime": "2999-09-08T16:00:00Z" 、 
        "ChargeType": "AfterPay" 、 
        "OppositeVpcInstanceId": "vpc-bp15opprpg0rg ****" 、 
        "HasReservationData": false、 
        "CrossBorder": false、 
        "OppositeInterfaceBusinessStatus": "通常" 、 
        "スペック": "ネガティブ" 、 
        "OppositeRouterType": "VRouter" 、 
        "役割": "AcceptingSide"
      }
    ]
  }, 
  "PageNumber":1、 
  "RequestId": "578448D7-9DCF-4703-8337-EF88DDF2C325" 、 
  "PageSize": 10
}
--------------------------- connect_router_interface ---------------------------
{
  "RequestId": "A5DBB86B-F6F5-4A53-899E-8CF4FEF510F2"
}
--------------------------- create_route_entry ---------------------------
{
  "RequestId": "70D896FE-986B-48EF-9734-17D6BDC8327A"
}
--------------------------- create_route_entry ---------------------------
{
  "RequestId": "A2233E25-4D6B-4713-A96F-E7CA745973CA"
}
--------------------------- delete_route_entry
{
  "RequestId": "464C62A4-EE65-4414-AF0A-4984AE6B8696"
}
-------------------------- delete_route_entry
{
  "RequestId": "0C11A332-969B-47CA-A683-5BFFECA28B3D"
}
deactivate_router_interface --------------------------- deactivate_router_interface ---------------------------
{
  "RequestId": "018305AD-FB9E-450A-91E8-3830634F5AC2"
}
deactivate_router_interface --------------------------- deactivate_router_interface ---------------------------
{
  "RequestId": "89B03203-9224-4CA3-8679-E0A49029A2D2"
}
--------------------------- delete_router_interface ---------------------------
{
  "RequestId": "FB0424CE-D0C7-438B-A3FA-BCF24EE9CC8A"
}
--------------------------- delete_router_interface ---------------------------
{
  "RequestId": "8A0A0BB6-A69D-461B-A117-14AD6670DECA"
}