0

I'd like to find a route table id associated with the given EC2 instance.

How can this be achieved using AWS CLI?


I've tried to use aws ec2 describe-vpcs, but the route tables are not there.

I'm using aws-cli/1.11.13.

1

You can achieve this by determining which subnet the ec2 instance belongs to, then check which route table the subnet is associated with.

#!/bin/bash

instanceId='YOU-INSTANCE-ID'

#finds the subnetId that the instance belongs to
subnetId=$(aws ec2 describe-instances \
           --instance-id $instanceId \
           --query "Reservations[*].Instances[].SubnetId" \
           --output text)

routingTableId=$(aws ec2 describe-route-tables \
                 --query "RouteTables[*].Associations[?SubnetId=='$subnetId'].RouteTableId" \
                 --output text)

echo $routingTableId
1

The route table is associated with VPC, which is associated with the instance.

Given $id shell variable has the instance ID, e.g.

id=i-0xyz # Replace i-0xyz with the real Instance ID.

here is the shell command to get VPCs associated with the instance and assign to $vpcs variable:

vpcs=$(aws ec2 describe-instances --instance-id $id --query 'Reservations[].Instances[].NetworkInterfaces[].VpcId' --output text)

Then to list the route tables associated with VPC, run:

aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$vpcs"

To get just the route ids, add: --query "RouteTables[].RouteTableId[]" parameter.

  • it's better to get the route table id from the perspective of the VPCID as done here if you're building something. You can't get the RTID from an EC2 if you are trying to launch one. – james6125 Nov 29 '18 at 22:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.