List Tag Value - EC2 Boto3

Viewed 14700

My understanding is I'm supposed to use resource when using Boto3 :)

The following returns all the key/value pairs; how would I get a specific key value? I'm looking print out the name given to the instance.

ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
    print (instance.tags)
1 Answers

You can use either the boto3 resource or client interfaces. The resource interface is a higher level which is easier (simpler) to work with. The client interface is lower layer and you have more fine grained control. Start off with using resource and later switch to client as you better understand Python / boto3 / AWS SDKs.

Here is an example that will print the Value value.

The key parts to understand is that instance.tags is an array of Python dict (dictionary). You need to loop thru this array to get to each "Value". When accessing a dict you use this syntax ['name_of_item'].

AWS stores tags as Key and Value. These are the names to use when processing the dict.

import boto3

ec2 = boto3.resource('ec2')

for instance in ec2.instances.all():
        print (instance.tags)
        for tag in instance.tags:
                print(tag['Value'])
Related