5

AWS now creates a default VPC and default subnet(s) for every instance launched. http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/default-vpc.html

You see the list of subnets either through the UI, or through the CLI

$ aws ec2 describe-subnets
{
    "Subnets": [
    ...
    ]
}

But the information on each subnet does not contain the list of instances associated with it.

{
        "AvailabilityZone": "us-east-1d",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "172.30.2.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": true,
        "State": "available",
        "SubnetId": "<subnet_id>",
        "VpcId": "<vpc_id>",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": []
},

How do I get the list of instances associated with a subnet?

Shankari
  • 153
  • 1
  • 3

3 Answers3

6

Here is an example with a querry for two subnets.

aws ec2 describe-instances --filters 'Name=subnet-id,Values=[subnet-12345678,subnet-90abcdef]'
Id2ndR
  • 61
  • 1
  • 2
0

You can take @Id2ndR's answer and pipe it to jq:

aws ec2 describe-instances\
   --filters 'Name=subnet-id,Values=[subnet-12345678,subnet-90abcdef]'\
| jq -r  '.Reservations[].Instances[] | .InstanceId'

to get a "pure" list of instances IDs.

Or something like:

aws ec2 describe-instances\
    --filters 'Name=subnet-id,Values=[subnet-12345678,subnet-90abcdef]'\
| jq -r  '.Reservations[].Instances[] | 
  (.Tags[]//[]|select(.Key=="Name")|.Value) as $name_tag | 
  (.Tags[]//[]|select(.Key=="Stack")|.Value) as $stack | 
  (.Tags[]//[]|select(.Key=="FQDN")|.Value) as $fqdn_tag | "\(.InstanceId)\t\. 
  (.LaunchTime)\t\($fqdn_tag)\t\(.PublicDnsName)\t\($name_tag)\t\($stack)"'`

to get more information.

Petro
  • 111
  • 2
0

One option is to retrieve the mapping from the instances instead - e.g.

$ aws ec2 describe-instances | grep subnet
                "SubnetId": "<subnet_id>",
                        "SubnetId": "<subnet_id>",
                "SubnetId": "<subnet_id>",
                        "SubnetId": "<subnet_id>",
                "SubnetId": "<subnet_id>",
                        "SubnetId": "<subnet_id>",
                ...

That seems pretty kludgy - since amazon already maintains this mapping, why can't they expose it with the subnet id as the key instead of the instance? Or am I missing something here?

Shankari
  • 153
  • 1
  • 3