本文介绍如何使用Python SDK在VPC路由器或边界路由器(VBR)上创建自定义路由条目。

前提条件

在创建自定义路由条目之前,您必须先完成以下操作:
  • 在华北3张家口地域创建了VPC和VSwitch。
  • 在华北3张家口地域创建了自定义路由的下一跳,下一跳类型可以为ECS实例、高可用虚拟IP、VPN网关、NAT网关、辅助弹性网卡或路由器接口。

背景信息

本次示例分为以下几步,创建自定义路由条目:
  1. 在华北3张家口地域创建一个名为sdk_route_table的自定义路由表。
  2. 查询专有网络vpc-8vb7ztbjqomi9xxxxxxxx下的VSwitch。
  3. 将新创建的自定义路由表与交换机vsw-8vbfqpcijj0d1xxxxxxxx进行绑定。
  4. 为新建的自定义路由表创建自定义路由条目,目的网络为168.168.0.0/16,下一跳类型为ECS实例,下一跳ID为i-8vbgsnt7046axxxxxxxx。
  5. 删除新创建的路由条目。
  6. 将新创建的自定义路由表与VSwitch解绑。
  7. 删除新创建的自定义路由表。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\sdk_lib文件夹。
  2. 使用编辑器打开consts.py文件,配置用户鉴权参数ACS_CLIENT
  3. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\vpc文件夹。
  4. 使用编辑器打开vpc_route_entry.py文件,根据实际情况配置相关参数,保存退出。
    #encoding=utf-8
    import sys
    import json
    import time
    
    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 RouteEntry(object):
        def __init__(self, client):
            self.client = client
    
        def create_route_entry(self, params):
            """
            create_route_entry: 创建route_entry路由条目
            官网API参考链接: https://help.aliyun.com/document_detail/36012.html
            """
            try:
                request = CreateRouteEntryRequest.CreateRouteEntryRequest()
                # 路由表ID
                request.set_RouteTableId(params['route_table_id'])
                # 自定义路由条目的目标网段
                request.set_DestinationCidrBlock(params['destination_cidr_block'])
                # 下一跳的类型
                request.set_NextHopType(params['nexthop_type'])
                # 下一跳实例的ID
                request.set_NextHopId(params['nexthop_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断router entry状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_route_entry_status,
                                            AVAILABLE, params['route_table_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def delete_route_entry(self, params):
            """
            delete_route_entry: 删除route_entry路由条目
            官网API参考链接: https://help.aliyun.com/document_detail/36013.html
            """
            try:
                request = DeleteRouteEntryRequest.DeleteRouteEntryRequest()
                # 路由条目所在的路由表的ID
                request.set_RouteTableId(params['route_table_id'])
                # 路由条目的目标网段
                request.set_DestinationCidrBlock(params['destination_cidr_block'])
                # 下一跳实例的ID
                request.set_NextHopId(params['nexthop_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                time.sleep(DEFAULT_TIME)
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_route_entry_vrouter(self, params):
            """
            describe_route_entry_vrouter: 查询route_entry路由条目
            官网API参考链接: https://help.aliyun.com/document_detail/36014.html
            """
            try:
                request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
                # 路由表所属的VPC路由器或边界路由器的ID
                request.set_VRouterId(params['vrouter_id'])
                # 路由表的ID
                request.set_RouteTableId(params['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_entry(self, route_table_id):
            """
            describe_route_entry: 查询route_entry路由条目
            官网API参考链接: https://help.aliyun.com/document_detail/36014.html
            """
            try:
                request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
                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_entry_status(self, route_table_id):
            """
            describe_route_entry_status: 查询route_entry路由条目当前状态
            """
            response = self.describe_route_entry(route_table_id)
            return response["RouteTables"]["RouteTable"][0]["RouteEntrys"]["RouteEntry"][0]["Status"]
    
    def main():
        client = ACS_CLIENT
        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-bp1e82xlhob2xxxxxxxx"
        params['nexthop_type'] = "Instance"
    
        params['vpc_id'] = "vpc-bp15opprpg0rgxxxxxxxx"
        params['vswitch_id'] = "vsw-bp1e67w26n2sjxxxxxxxx"
    
        #创建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())
  5. 进入vpc_route_entry.py所在的目录,执行如下命令,运行创建自定义路由条目示例。
    python vpc_route_entry.py
    系统显示类似如下:
    ---------------------------create_route_table---------------------------
    {
      "RouteTableId": "vtb-8vbn7px9zxwr2xxxxxxxx",
      "RequestId": "8B351EE1-614F-44E4-93AF-1CADA4BF02E8"
    }
    
    ---------------------------describe_vswitch_attribute---------------------------
    
    {
      "Status": "",
      "NetworkAclId": "",
      "VpcId": "",
      "Description": "",
      "Ipv6CidrBlock": "",
      "CreationTime": "",
      "CloudResources": {
        "CloudResourceSetType": []
      },
      "ZoneId": "",
      "ResourceGroupId": "",
      "VSwitchId": "",
      "RequestId": "5E199415-BBA3-443D-B1EC-06341FE267F4",
      "VSwitchName": "",
      "CidrBlock": ""
    }
    
    ---------------------------associate_route_table---------------------------
    {
      "RequestId": "5F33E444-5CCD-4677-91AB-3E234A9A64E4"
    }
    
    ---------------------------create_route_entry---------------------------
    {
      "RequestId": "D6035ECA-DD81-4FAB-B084-55BE60FB18ED"
    }
    
    ---------------------------delete_route_entry---------------------------
    {
      "RequestId": "54108FD7-8609-4111-919D-B2983466F480"
    }
    
    ---------------------------unassociate_route_table---------------------------
    {
      "RequestId": "0F36A76A-1E54-41DC-852E-1D970FDE8F3F"
    }
    
    ---------------------------delete_route_table---------------------------
    {
      "RequestId": "F3151A59-4F90-4531-AFDC-B7B7CF70A8C1"
    }