本文介绍如何使用Alibaba Cloud SDK for Python创建自定义路由表。

前提条件

在使用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. 在华北3(张家口)地域创建一个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
    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 CreateRouteEntryRequest
    from aliyunsdkvpc.request.v20160428 import DeleteRouteEntryRequest
    from aliyunsdkvpc.request.v20160428 import DescribeRouteTablesRequest
    from sdk_lib.exception import ExceptionHandler
    from sdk_lib.check_status import CheckStatus
    from sdk_lib.common_util import CommonUtil
    from sdk_lib.sdk_vswitch import VSwitch
    from sdk_lib.sdk_route_table import RouteTable
    from sdk_lib.consts import *
    
    class RouteTable(object):
        def __init__(self, client):
            self.client = client
    
    
        def create_route_table(self, params):
            """
            create_route_table: 创建一个自定义路由表
            官网API参考链接: https://help.aliyun.com/document_detail/87586.html
            """
            try:
                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(response)
                route_table_id = response_json['RouteTableId']
                # 判断route table状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.describe_route_table_status,
                                            route_table_id, route_table_id):
                    return 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内的交换机绑定
            官网API参考链接: https://help.aliyun.com/document_detail/87599.html
            """
            try:
                request = AssociateEipAddressRequest.AssociateEipAddressRequest()
                request.set_action_name("AssociateRouteTable")
                # 路由表ID
                request.add_query_param("RouteTableId", params['route_table_id'])
                # 要绑定的交换机ID
                request.add_query_param("VSwitchId", params['vswitch_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                time.sleep(DEFAULT_TIME * 5)
                return 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: 将路由表和交换机解绑
            官网API参考链接: https://help.aliyun.com/document_detail/87628.html
            """
            try:
                request = UnassociateEipAddressRequest.UnassociateEipAddressRequest()
                request.set_action_name("UnassociateRouteTable")
                # 路由表ID
                request.add_query_param("RouteTableId", params['route_table_id'])
                # 要解绑的交换机ID
                request.add_query_param("VSwitchId", params['vswitch_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                time.sleep(DEFAULT_TIME * 5)
                return 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.html
            """
            try:
                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(response)
                # 判断route table是否被删除成功
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.describe_route_table_status,
                                            '', params['route_table_id']):
                    return 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.html
            """
            try:
                request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
                # 路由表的ID
                request.set_RouteTableId(route_table_id)
                response = self.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 describe_route_table_status(self, route_table_id):
            """
            describe_route_table_status: 查询路由表状态
            """
            response = self.describe_route_table(route_table_id)
            if len(response["RouteTables"]["RouteTable"]) == 0:
                return ''
            return response["RouteTables"]["RouteTable"][0]["RouteTableId"]
    
    def main():
        #client参数配置
       # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
       # 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
       # 本示例通过阿里云Credentials工具从环境变量中读取AccessKey,来实现API访问的身份验证。如何配置环境变量,请参见https://help.aliyun.com/document_detail/378659.html。
       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>')
    
        vswitch = VSwitch(client)
        route_table = RouteTable(client)
        route_entry = RouteEntry(client)
    
        params = {}
        params['route_table_name'] = "sdk_route_table"
        params['destination_cidr_block'] = "0.0.0.0/0"
        params['nexthop_id'] = "i-xxx"
        params['nexthop_type'] = "Instance"
    
        params['vpc_id'] = "vpc-xxx"
        params['vswitch_id'] = "vsw-xxx"
    
        #创建route table
        route_table_json = route_table.create_route_table(params)
        CommonUtil.log("create_route_table", route_table_json)
    
        #查询vSwitch
        vswitch_json = vswitch.describe_vswitch_attribute(params)
        CommonUtil.log("describe_vswitch_attribute", vswitch_json)
    
        #route table绑定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)
    
        #route table解绑vSwitch
        unassociate_json = route_table.unassociate_route_table(params)
        CommonUtil.log("unassociate_route_table", unassociate_json)
    
        #删除route table
        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---------------------------

{
  "Status": "Available",
  "NetworkAclId": "",
  "VpcId": "vpc-8vbebihln001gxxxxxxxx",
  "Description": "",
  "RouteTable": {
    "RouteTableId": "vtb-8vb65a5hqy8pcxxxxxxxx",
    "RouteTableType": "System"
  },
  "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"
}