Use Boto3 to Update a Tag on Many Hosts

I was recently asked to update a single tag in all of our 800 hosts only if there was already another tag present. So I need to look at all hosts, if I find a tag called ‘Type’ that contains the text ‘copy-from’ or ‘copy-from’ is in the value at all, then I need to add another new tag called ‘no-copy’ and set its value to ‘true’. Well, there was no way I was going to manually do this using the AWS GUI. So here is an example of a boto3 script that does the work.

# Import boto and create an ec2 client session
import boto3
ec2 = boto3.client('ec2',
                    region_name='us-east-1',
                    aws_access_key_id='xxxxxxxxxxxxxx',
                    aws_secret_access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)
# I'm not using a paginator here since I know I have under 1000 hosts.
# This code will not work if you have more than 1k hosts. 
# You need to use a paginator for more than 1k hosts or you will not list all hosts. 
response = ec2.describe_instances()

# iterate over each host. 
for each_res in response['Reservations']:
    for each_inst in each_res['Instances']:
        # I set this matchhost as a flag as I iterate through each host. 
        matchhost = False
        # On each host, I iterate through all the tags on the host.   
        for each_tag in each_inst['Tags']:
            # On each tag, if the key and values match my target values, then I set matchhost to True. 
            if each_tag['Key'] == 'Type' and 'copy-from' in each_tag['Value']:
                matchhost = True
        # Now that I've run through all tags on this 1 host, if I matched the values, then I create a new tag. 
        if matchhost:
            response = ec2.create_tags(
                Resources=[each_inst['InstanceId']],
                Tags = [
                    {
                        'Key': 'no-copy',
                        'Value': 'true'
                    }
                ]
            )

That’s all there is to it. I let the script run and in a few minutes, the task was complete.

Tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
24 − 18 =