This topic describes how to use Alibaba Cloud SDK for Python to create a custom route table.

Prerequisites

Before you run Alibaba Cloud SDK for Python, make sure that the following requirements are met:
  • An Alibaba Cloud account and the AccessKey pair are obtained. You can create and view your AccessKey pair on the Security Management page of the Alibaba Cloud Management Console.
  • Make sure that Alibaba Cloud SDK for Python is installed. For more information, see aliyun-python-sdk-vpc 3.0.11.
  • The VPC Python example library is downloaded.
    Go to the directory where the setup.py file is stored, and run the following command to initialize the environment:
    python setup.py install

Background information

The code sample in this topic includes the following operations:
  1. Create a virtual private cloud (VPC) in the China (Zhangjiakou) region.
  2. Create a vSwitch in the VPC.
  3. Create a custom route table named sdk_route_table.
  4. Query the vSwitch.
  5. Associate the custom route table with the vSwitch that belongs to the same VPC.
  6. Disassociate the custom route table from the vSwitch that belongs to the same VPC.
  7. Delete the custom route table.
  8. Delete the vSwitch.
  9. Delete the VPC.

Procedure

  1. In the downloaded SDK directory, open the $aliyun-openapi-python-sdk-examples\sdk_examples\examples\vpc folder.
  2. Open the vpc_route_table.py file in your text editor. Set the required parameters, save the configurations, and then exit the editor.
    The following sample code is provided:
    #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: Create a route.
    
            """
            try:
                request = CreateRouteEntryRequest.CreateRouteEntryRequest()
                # The ID of the route table.
                request.set_RouteTableId(params['route_table_id'])
                # The destination CIDR block of the route.
                request.set_DestinationCidrBlock(params['destination_cidr_block'])
                # The type of next hop.
                request.set_NextHopType(params['nexthop_type'])
                # The ID of the instance that is specified as the next hop of the route.
                request.set_NextHopId(params['nexthop_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                # Check whether the route is in the Available state.
                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: Delete the route.
    
            """
            try:
                request = DeleteRouteEntryRequest.DeleteRouteEntryRequest()
                # The ID of the route table to which the route belongs.
                request.set_RouteTableId(params['route_table_id'])
                # The destination CIDR block of the route.
                request.set_DestinationCidrBlock(params['destination_cidr_block'])
                # The ID of the instance that is specified as the next hop of the route.
                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: Query the route.
    
            """
            try:
                request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
                # The ID of the vRouter or virtual border router (VBR) to which the route table belongs.
                request.set_VRouterId(params['vrouter_id'])
                # The ID of the route table.
                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: Query the route.
    
            """
            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: Query the state of the route.
    
            """
            response = self.describe_route_entry(route_table_id)
            return response["RouteTables"]["RouteTable"][0]["RouteEntrys"]["RouteEntry"][0]["Status"]
    
    def main():
        # The configuration of the client.
        client = AcsClient(
                '<your-access-key-id>',
                '<your-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"
    
        # Create a route table.
        route_table_json = route_table.create_route_table(params)
        CommonUtil.log("create_route_table", route_table_json)
    
        # Query the vSwitch.
        vswitch_json = vswitch.describe_vswitch_attribute(params)
        CommonUtil.log("describe_vswitch_attribute", vswitch_json)
    
        # Associate the route table with the 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 a route.
        create_route_entry_json = route_entry.create_route_entry(params)
        CommonUtil.log("create_route_entry", create_route_entry_json)
    
        # Delete the route.
        delete_route_entry_json = route_entry.delete_route_entry(params)
        CommonUtil.log("delete_route_entry", delete_route_entry_json)
    
        # Disassociate the route table from the vSwitch.
        unassociate_json = route_table.unassociate_route_table(params)
        CommonUtil.log("unassociate_route_table", unassociate_json)
    
        # Delete the 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. Go to the directory where the vpc_route_table.py file is stored, and run the following command to create a custom route table:
    python vpc_route_table.py

Result

The following output is returned:
---------------------------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"
}