Home > front end >  Boto3 Missing Contact Tag Values, No Errors
Boto3 Missing Contact Tag Values, No Errors

Time:07-19

I have this portion of the script that supposed to return a contact value but the script is running and no contact value is printed. I have tried to move the second try statement back by one indent but the outcome is still the same. It should be printing out the "instance_contacttag" as the contact value. I'm sure it's something simple but I can't seem to get, thanks.

for reservation in reservations:
        # tags = {}
        for instance in reservation['Instances']:
            tags = {}
            instance_ids = instance['InstanceId']
            print(instance_ids   " is the instance id within the instance_ids dictionary")
            try:
                for tag in instance['Tags']:
                    tags[tag['Key']] = tag['Value']
                    # print(instance['Tags'])

                    if tag['Key'] == 'Name':
                        # print(tag['Value'])
                        instance_nametag = tag['Value']
            except:
                pass
                
                try: 
                    if tag['Key'] == 'contact':
                        instance_contacttag = tag['Value']
                        print(instance_contacttag)
                                         
                except:
                    print("CONTACT TAG MISSING")

CodePudding user response:

The enumeration of the tags won't produce an exception, meaning, if the item isn't in the list, you just won't see the item.

It's much easier to convert the list of tags to a dictionary, and perform simple dictionary look ups to see if an item is present:

import boto3
ec2 = boto3.client('ec2')
data = ec2.describe_instances()
reservations = data['Reservations']

for reservation in reservations:
    for instance in reservation['Instances']:
        tags = instance['Tags']
        # Convert the tag list to a Python dictionary to make looking up tags easier
        tags = {x['Key']: x['Value'] for x in tags}

        # Show the Instance ID
        instance_ids = instance['InstanceId']
        print(instance_ids   " is the instance id within the instance_ids dictionary")

        if 'Name' in tags:
            instance_nametag = tags['Name']
            print("Name: "   instance_nametag)

        # Look for the 'contact' tag
        if 'contact' in tags:
            instance_contacttag = tags['contact']
            print("Contact: "   instance_contacttag)
        else:
            # It's not present, show a warning
            print("CONTACT TAG MISSING")
  • Related