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

:カスタムルートテーブルの作成

最終更新日:Jan 02, 2024

このトピックでは、Alibaba Cloud SDK for Pythonを使用してカスタムルートテーブルを作成する方法について説明します。

前提条件

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. sdk_route_tableという名前のカスタムルートテーブルを作成します。
  4. vSwitchを照会します。
  5. カスタムルートテーブルを同じVPCに属するvSwitchに関連付けます。
  6. 同じVPCに属するvSwitchからカスタムルートテーブルの関連付けを解除します。
  7. カスタムルートテーブルを削除します。
  8. vSwitchを削除します。
  9. VPCを削除します。

手順

  1. ダウンロードしたsdkディレクトリにあるaliyun-openapi-python-SDK-examples\sdk_examples\examples\vpcフォルダーを開きます。
  2. テキストエディターでvpc_route_table.pyファイルを開きます。 必要なパラメーターを設定し、設定を保存してから、エディターを終了します。
    次のサンプルコードが表示されます。
    #encoding=utf-8
    インポートsys
    jsonのインポート
    インポート時間
    
    alibabacloud_credentials.clientからCredClientとしてのインポートクライアント
    からaliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    aliyunsdkvpc.request.v20160428からCreateRouteEntryRequestをインポート
    aliyunsdkvpc.request.v20160428からDeleteRouteEntryRequestをインポート
    aliyunsdkvpc.request.v20160428からDescribeRouteTablesRequestをインポート
    sdk_lib.exception import ExceptionHandlerから
    sdk_lib.check_statusからCheckStatusをインポートする
    sdk_lib.common_utilインポートからCommonUtil
    sdk_lib.sdk_vswitchからVSwitchをインポート
    sdk_lib.sdk_route_tableからRouteTableをインポート
    sdk_lib.consts import * から
    
    クラスRouteTable (オブジェクト):
        def __init__(self, client):
            self.client=クライアント
    
    
        def create_route_table(self, params):
            """
            create_route_table: カスタムルートテーブルを作成します。
            APIリファレンス: https://help.aliyun.com/document_detail/87586.htmlhttps:// www.alibabacloud.com/help/virtual-private-cloud/latest/createroutetable
            """
            試してみてください。
                request = CreateRouteEntryRequest.CreateRouteEntryRequest()
                request.set_action_name("CreateRouteTable")
                # カスタムルートテーブルが属するVPCのID。
                request.add_query_param("VpcId", params['vpc_id'])
                # ルートテーブルの名前。
                request.add_query_param("RouteTableName", params['route_table_name '])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                route_table_id = response_json['RouteTableId']
                # ルートテーブルが使用可能かどうかを確認します。
                CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.de scribe_route_table_status、
                                            route_table_id、route_table_id):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def associate_route_table(self, params):
            """
            associate_route_table: カスタムルートテーブルを同じVPC内のvSwitchに関連付けます。
            APIリファレンス: https://help.aliyun.com/document_detail/87599.htmlhttps:// www.alibabacloud.com/help/virtual-private-cloud/latest/associateroutetable
            """
            試してみてください。
                request = AssociateEipAddressRequest。AssociateEipAddressRequest()
                request.set_action_name("AssociateRouteTable")
                # ルートテーブルのID。
                request.add_query_param("RouteTableId", params['route_table_id '])
                # 関連付けるvSwitchのID。
                request.add_query_param("VSwitchId", params['vswitch_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                time.sleep(DEFAULT_TIME * 5)
                response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def unassociate_route_table(self, params):
            """
            unassociate_route_table: vSwitchからルートテーブルの関連付けを解除します。
            APIリファレンス: https://help.aliyun.com/document_detail/87628.htmlhttps:// www.alibabacloud.com/help/virtual-private-cloud/latest/unassociateroutetable
            """
            試してみてください。
                request = UnassociateEipAddressRequest。UnassociateEipAddressRequest()
                request.set_action_name("UnassociateRouteTable")
                # ルートテーブルのID。
                request.add_query_param("RouteTableId", params['route_table_id '])
                # 関連付けを解除するvSwitchのID。
                request.add_query_param("VSwitchId", params['vswitch_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads (レスポンス)
                time.sleep(DEFAULT_TIME * 5)
                response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def delete_route_table(self, params):
            """
            delete_route_table: カスタムルートテーブルを削除します。
            APIリファレンス: https://help.aliyun.com/document_detail/87601.htmlhttps:// www.alibabacloud.com/help/virtual-private-cloud/latest/deleteroutetable
            """
            試してみてください。
                request = DeleteRouteEntryRequest.DeleteRouteEntryRequest()
                request.set_action_name("DeleteRouteTable")
                # ルートテーブルのID。
                request.add_query_param("RouteTableId", params['route_table_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_route_table_status、
                                            ''、params ['rout_table_id ']):
                    response_jsonを返します
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_route_table(self, route_table_id):
            """
            describe_route_table: ルートテーブルを照会します。
            APIリファレンス: https://help.aliyun.com/document_detail/87602.htmlhttps:// www.alibabacloud.com/help/virtual-private-cloud/latest/describeroutetablelist
            """
            試してみてください。
                request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
                # ルートテーブルのID。
                request.set_RouteTableId(route_table_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_route_table_status(self, route_table_id):
            """
            describe_route_table_status: ルートテーブルのステータスを照会します。
            """
            response = self.de scribe_route_table(route_table_id)
            if len(response["RouteTables"]["RouteTable"]) == 0:
                return''
            リターンレスポンス ["RouteTables"]["RouteTable"][0]["RouteTableId"]
    
    def main():
        # クライアントの設定。
       # 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()
    
       # Create an AcsClient instance.
       client = AcsClient(access_key_id, access_key_secret, '<your-region-id>')
    
        vswitch = VSwitch (クライアント)
        route_table = RouteTable (クライアント)
        route_entry = RouteEntry (クライアント)
    
        params = {}
        params ['rout_table_name '] = "sdk_route_table"
        params ['_destination cidr_block '] = "0.0.0.0/0"
        params [nexthop_id'] = "i-xxx"
        params['nexthop_type'] = "インスタンス"
    
        params['vpc_id'] = "vpc-xxx"
        params['vswitch_id'] = "vsw-xxx"
    
        # ルートテーブルを作成します。
        route_table_json = route_table.create_route_table(params)
        CommonUtil.log("create_route_table", route_table_json)
    
        # vSwitchを照会します。
        vswitch_json = vswitch.de scribe_vswitch_attribute(params)
        CommonUtil.log("describe_vswitch_attribute", vswitch_json)
    
        # ルートテーブルをvSwitchに関連付けます。
        params['route_table_id '] = route_table_json['RouteTableId']
        associate_json = route_table.associate_route_table(params)
        CommonUtil.log("associate_route_table", associate_json)
    
        # ルートを作成します。
        create_route_entry_json = route_entry.create_route_entry(params)
        CommonUtil.log("create_route_entry", create_route_entry_json)
    
        # ルートを削除します。
        delete_route_entry_json = route_entry.delete_route_entry(params)
        CommonUtil.log("delete_route_entry", delete_route_entry_json)
    
        # vSwitchからルートテーブルの関連付けを解除します。
        unassociate_json = route_table.unassociate_route_table(params)
        CommonUtil.log("unassociate_route_table", unassociate_json)
    
        # ルートテーブルを削除します。
        delete_route_table_json = route_table.delete_route_table(params)
        CommonUtil.log("delete_route_table", delete_route_table_json)
    
    
    if __name__ == "__main__":
        sys.exit(main()) 
  3. vpc_route_table.pyファイルが保存されているディレクトリに移動し、次のコマンドを実行してカスタムルートテーブルを作成します。
    python vpc_route_table.py

結果

次の出力が返されます。
--------------------------- create_vpc ---------------------------
{
  "ResourceGroupId": "rg-acfmxazxxxxxxxx" 、
  "RouteTableId": "vtb-8vb65a5hqy8pcxxxxxxxx" 、
  "VRouterId": "vrt-8vbbbiftzizc3xxxxxxxx" 、
  "VpcId": "vpc-8vbebihln001gxxxxxxxx" 、
  "RequestId": "862F279B-4A27-4300-87A1-047FB9961AF2"
}

--------------------------- create_vswitch ---------------------------
{
  "VSwitchId": "vsw-8vb30klhn2is5xxxxxxxx" 、
  "RequestId": "1DA17173-CB61-4DCE-9C29-AABFDF3001A6"
}

--------------------------- create_route_table ---------------------------
{
  "RouteTableId": "vtb-8vbc4iwpo13apxxxxxxxx" 、
  "RequestId": "01E66E67-7801-4705-A02A-853BA7EEA89F"
}

--------------------------- describe_vswitch_attribute ---------------------------

{
  "ステータス": "利用可能" 、
  "NetworkAclId": "" 、
  "VpcId": "vpc-8vbebihln001gxxxxxxxx" 、
  "Description": "",
  "RouteTable": {
    "RouteTableId": "vtb-8vb65a5hqy8pcxxxxxxxx" 、
    "RouteTableType": "システム"
  },
  "CidrBlock": "172.16.0.0/16" 、
  "CreationTime": "2019-04-12T03:08:43Z" 、
  "CloudResources": {
    "CloudResourceSetType": []
  },
  "ZoneId": "cn-zhangjiakou-b" 、
  "ResourceGroupId": "rg-acfmxazbxxxxxxxx" 、
  "VSwitchId": "vsw-8vb30klhn2is5xxxxxxxx" 、
  "RequestId": "C5A20BA3-E998-498D-8900-35AE5FDFFB77" 、
  "Ipv6CidrBlock": "" 、
  "VSwitchName": "" 、
  "AvailableIpAddressCount": 252、
  "IsDefault": false
}

--------------------------- associate_route_table ---------------------------
{
  "RequestId": "5FC0143B-D34B-47DC-8D49-AFD222EA5876"
}

--------------------------- unassociate_route_table ---------------------------
{
  "RequestId": "F0194718-6E4C-496C-9DA8-1B88DF1D6FAD"
}

--------------------------- delete_route_table
{
  "RequestId": "B5C068A6-137C-4337-8E3A-9E30E1726703"
}

--------------------------- delete_vswitch ---------------------------
{
  "RequestId": "26DEDBF8-2F0D-4A13-8CB3-23A84C947704"
}

--------------------------- delete_vpc ---------------------------
{
  "RequestId": "E1B2641F-5911-40E4-9F36-CC0B2EDD1747"
}