2
votes

I want to list tags for all ec2 resources(customer-gateway | dhcp-options | image | instance | internet-gateway | network-acl | network-interface | reserved-instances | route-table | security-group | snapshot | spot-instances-request | subnet | volume | vpc | vpn-connection and vpn-gateway).

The following code lists all the resources for my ec2 client which have tags:

session = boto3.Session(profile_name='default')
ec2Client = session.client('ec2', region_name='eu-west-2') 
allTags = ec2Client.describe_tags()['Tags']
for tag in allTags:
    print tag

PROBLEM

The problem here is that only resources like in case of 'instances', the instances which do not have tags are not included. If there are 5 instances in ec2, 3 with tags and 2 without tags, the above code will list only those 3 instances with tags.

DESIRED OUTPUT

I want all the resources (instances, VPCs, subnet, security groups etc.), to be listed whether the tags are defined or not. If there are tags it shows tags, if not I still want it to be included in the result without tags.

One way is to use describe_xxx method for each resource to get the reservations and look for tags, but I would have to call it for every resource (like describe_instances(), describe_snapshots, describe_security_groups() etc.), which, in my opinion is not so cleaned and generic way solution.

QUESTION

Is there any way using boto3 library to list all the resources, if the resources have tags show the tags too if not then show the resources only?

1
I was referring to this documentation here: boto3.readthedocs.io/en/latest/reference/services/ec2.html - wafers

1 Answers

0
votes

As far as I know, boto3 does not offer a describe_all method. To achieve your desired result, if I understand it correctly, you will have to separately describe all object types, i.e. describe_vpcs, describe_instances, etc, and then look for the tags in the resulting data structures.

For example, One could construct a single data structure from all the resulting method calls (describe_instances, describe_vpcs, describe_subnets, etc.) which will look like:

{
  Vpcs: [{... Tags: [{...}]}]
  Instances: [{... Tags: [{...}]}]
  Subnets: [{... Tags: [{...}]}]
  ...
}

I believe this is the closest match to the object you are referring to in your question.