Home > database >  EC2 index tags works but doesn't for iam user, is the syntax off?
EC2 index tags works but doesn't for iam user, is the syntax off?

Time:08-17

I have this piece of code and it works just fine but I don't understand exactly how the tags are converted into a dict, you have the part where you have "tags = instance['Tags']" which is fine, then the next line "tags = {x['Key']: x['Value'] for x in tags}" which throws me off because how are you able to define tags twice not get an error like "errorMessage": "string indices must be integers", I've tried this with other clients like 'iam' and code doesn't work, code is working for 'ec2' tags and not working for 'iam' tags, are they not essentially the same thing? I know, I have much to learn but any guidance would be appreciated. Thanks.

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}
        print (tags)

The 'iam' version is below

iam_client = boto3.client('iam')
response = iam_client.list_users()


def lambda_handler(event,context):
    for user in response['Users']:
        tags = iam_client.list_user_tags(UserName = user['UserName'])
        tags = {x['Key']: x['Value'] for x in tags}
        if tags['Tags']:
            for tag in tags['Tags']:
                print(tags)

CodePudding user response:

You get the error because it should be:

tags = {x['Key']: x['Value'] for x in tags["Tags"]}

Also you keep overwriting your tags,

  • Related