All Products
Search
Document Center

Virtual Private Cloud:Create a custom route

Last Updated:Mar 07, 2024

This topic describes how to use Alibaba Cloud SDK for Python to create a custom route on a vRouter of a virtual private cloud (VPC) or on a virtual border router (VBR).

Prerequisites

Before you use 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.
  • Alibaba Cloud SDK for Python is installed.
  • 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 custom route table named sdk_route_table in the China (Zhangjiakou) region.

  2. Query vSwitches in the VPC named vpc-8vb7ztbjqomi9mh1q****.

  3. Associate the custom route table with the vSwitch named vsw-8vbfqpcijj0d13eaq****.

  4. Add a route to the custom route table. The destination CIDR block is 168.168.0.0/16. The next hop is an Elastic Compute Service (ECS) instance. The ID of the next hop is i-8vbgsnt7046a2qm****.

  5. Delete the route.

  6. Disassociate the custom route table from the vSwitch.

  7. Delete the custom route table.

Procedure

  1. Open the aliyun-openapi-python-sdk-examples\sdk_examples\examples\vpc folder in the downloaded SDK directory.

  2. Use the editor to open the vpc_route_entry.py file, configure the parameters, then save and exit.

    The following sample code is displayed:

    # 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 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 next hop instance.
                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 next hop instance.
                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 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 status of the route.
    
            """
            response = self.describe_route_entry(route_table_id)
            return response["RouteTables"]["RouteTable"][0]["RouteEntrys"]["RouteEntry"][0]["Status"]
    
    def main():
        # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To prevent security risks, we recommend that you call API operations or perform routine O&M as a RAM user. 
        # We do not recommend that you save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of your resources may be compromised. 
        # In this example, the AccessKey pair is obtained by using credentials provided by Alibaba Cloud. The pair is used to implement authentication for API access. For more information about how to configure environment variables, see https://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(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_entry.py file is stored, and run the following command to create a route:

    python vpc_route_entry.py

Result

The following output is returned:

---------------------------create_route_table---------------------------
{
  "RouteTableId": "vtb-8vbn7px9zxwr2mh1q****",
  "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"
}