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
.
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
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.