0

I am fairly new to AWS Python Boto3. I am trying to figure a way to replace existing tags value with a different value.

import boto3
session = boto3.session.Session(aws_access_key_id=aws_access_id, aws_secret_access_key=aws_secret, region_name='us-east-1')

ec2 = session.resource('ec2')
instances = ec2.instances.filter(
    Filters=[{'Name':'tag:1', 
             'Values':['2']}
])

The code above will find all instances with the mentioned tag but I am not sure how to replace the tags with a different value.

Any help is appreciated.

1 Answer 1

1

Use create_tags. Despite the 'create' name, it also updates tags.

Example:

import boto3

client = boto3.client('ec2')

response = client.create_tags(
    Resources=[
        'i-0397e32da88889999',
    ],
    Tags=[
        {
            'Key': 'Env',
            'Value': 'QA'
        },
    ]
)
4
  • Thanks for your fast response. We have a lot of instances that need to be updated so I thought of filtering instances first by tags then update the value. Is there a way to achieve that or any alternate ways?
    – Solution
    Jan 17, 2019 at 18:24
  • Filtering is a good way to get the list of resources that need updated tags. You can then invoke a single create_tags call, passing in a list of resource IDs (up to 1000). Note that the list of resource IDs can include resources other than EC2 instances, if you like. That's why it uses the generic term 'resource ID' rather than "EC2 instance ID".
    – jarmod
    Jan 17, 2019 at 18:44
  • By filtering the instances by tags, it should display the result of the instances with that specified tags however, how do I replace the value? I believe the if else statement should work but I am unsure how will the syntax looks like. Any guidance will be appreciated. Thanks!
    – Solution
    Jan 17, 2019 at 21:35
  • Not sure I fully understand the problem here, but if you use the SDK to get a list of resources, say EC2 instances, that have the tags of interest, then simply create a new list that contains just the resource IDs (the instance IDs in the case of EC2 instances), and then pass that list as the Resources parameter to create_tags().
    – jarmod
    Jan 21, 2019 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.