2
votes

I can easily list all security group names using the following codes:

import boto3
ec2_client = boto3.client('ec2')

print('All Security Groups:')
print('----------------')
sg_all = ec2_client.describe_security_groups()
for sg in sg_all['SecurityGroups'] :
    print(sg['GroupName'])

I am trying to list all the subnet names the same way like:

print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    print(sn['SubnetName'])

Here, variable sn gets all each subnet including all properties and tags but cannot find the right property name for subnet like GroupName.

I can use boto3.resource('ec2') or the following codes but for simplicity I am looking for the similar method I used above to list all security groups:

print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    for tag in sn['Tags']:
        if tag['Key'] == 'Name':
            print(tag['Value'])

Any help is greatly appreciated.

2

2 Answers

3
votes

Amazon VPC Subnets do not have a "Name" field (whereas Security Groups do have a GroupName field).

In the management console, you can see that Security Groups have two columns: Group Name and Name. The Name field is actually the value of the tag called Name.

Subnets, on the other hand, only have the Name tag.

Tip: An easy way to see what information is available is by looking at the AWS Command-Line Interface (CLI) documentation for describe-subnets.

2
votes
import boto3
ec2_client = boto3.client('ec2')
print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    print(sn['SubnetId'])