rp346
rp346

Reputation: 7068

boto3 add/update tags to existing AMI

I am trying to update Tags to AMI with following code.

import boto3

client = boto3.client("ec2")

amis = client.describe_images(Owners=['self'])['Images']

for ami in amis:
    creation_date=ami['CreationDate']
    ami_id = ami['ImageId']
    ami_name = ami['Name']
    try:
        for tag in ami['Tags']:
            if tag['Key'] != 'Servie' and tag['Value'].startswith('lc'):
                print(ami['ImageId'], tag, creation_date)
                ami.create_tags( DryRun=False, Tags=[ { 'Key': 'Service', 'Value': 'it' }, ] )
    except Exception as e:
        print(e)

But I am getting following error

'dict' object has no attribute 'create_tags'

What I am missing here ?

Upvotes: 0

Views: 407

Answers (1)

Bert Blommers
Bert Blommers

Reputation: 2123

The describe_images returns a list of dictionaries, like this:

[{info for ami1}, {info for ami2}, ..]

When looping over that list using for ami in amis:, the variable ami becomes a dictionary containing all the information for that AMI. You can use print(ami) to get a better idea of all the fields that are returned.

Because it is a dictionary, it is not possible to call any EC2 actions on that variable itself. What you probably want is:

client.create_tags(
  Resources=[ami["ImageId"]],
  Tags=[...]
)

If you were using boto3.resource to list all images, you would get a list of Image-objects back. It is possible to call create_tags directly on the Image-object.

ec2 = boto3.resource('ec2')
for ami in ec2.images.filter(Owners=["self"]):
    ami.create_tags(..)

See

Upvotes: 1

Related Questions