How do I add routes to the main route table in my VPC with AWS CloudFormation?
Last updated: 2019-05-08
I want to use AWS CloudFormation to add routes to the main route table that's created by default when my Amazon Virtual Private Cloud (Amazon VPC) is created using AWS CloudFormation.
AWS CloudFormation can't recognize the main route table that's created by default when you create a VPC using AWS CloudFormation. This means that information about the route table can't be passed between your VPC and AWS CloudFormation. Therefore, you can't add or remove routes from the main route table, because you can't reference the main route table from your AWS CloudFormation template.
To resolve this issue, you can use an AWS Lambda-backed custom resource in an AWS CloudFormation template. The template uses a Lambda function to retrieve the main route table ID associated with your VPC.
1. Download the RouteTable.template and Routetable.py files from the AWS GitHub repository.
2. Create a zip file called Routetable.zip for the Lambda function. See the following example:
-> Routetable.zip | |-> Routetable.py
Important: Be sure that Routetable.py is located at the root level of the zip file.
3. Upload the zip file to an Amazon Simple Storage Service (Amazon S3) bucket that's in the same AWS Region as your AWS CloudFormation stack with the Amazon S3 console. To upload the zip file using the AWS Command Line Interface (AWS CLI), run the following command from the Routetable.zip folder:
aws s3 cp ./Routetable.zip s3://awsexamplebucket1/Routetable.zip
4. To launch your stack with the RouteTable.template file, use the AWS CloudFormation console or the following AWS CLI command:
aws cloudformation create-stack --stack-name myvpcstack --template-body file://RouteTable.template --parameters ParameterKey=Bucket,ParameterValue=awsexamplebucket1 ParameterKey=Key,ParameterValue=Routetable.zip ParameterKey=Lambdahandler,ParameterValue=Routetable --capabilities CAPABILITY_NAMED_IAM --region us-east-1
Important: When you create or update your AWS CloudFormation stack, you must pass in the name of the Amazon S3 bucket (awsexamplebucket1) where you uploaded the zip file, the zip file name (Routetable.zip), and name of the file where you created the Lambda function (Routetable) as parameters.
The stack creates a VPC, and then uses a Lambda-backed custom resource to fetch the main route table ID of the VPC. The ID is used in AWS::EC2::Route to add a public route to the main route table. Then, the stack outputs display the route table ID.