Categories
Amazon Web Services Cloud Architecting Python

AWS Tag Checker

I wrote this script this morning as I was creating a new web server. I realized that I had been forgetting to add my “Backup” tag to my instances so that they would automatically be backed up via AWS Backup.

This one is pretty straight forward. Utilizing Boto3 this script will iterate over all of your instances and check them for the tag specified on line 8. If the tag is not present it will then add the tag that is defined by JSON in $response.

After that is all done it will iterate over the instances again to check that the tag has been added. If a new instance has been added or it failed to add the tag it will print out a list of instance ID’s that do not have the tag.

Here is the script:

import boto3


ec2 = boto3.resource('ec2')
inst_describe = ec2.instances.all()

for instance in inst_describe:
    tag_to_check = 'Backup'
    if tag_to_check not in [t['Key'] for t in instance.tags]:
        print("This instance is not tagged: ", instance.instance_id)
        response = ec2.create_tags(
            Resources= [instance.instance_id],
            Tags = [
                {
                    'Key': 'Backup',
                    'Value': 'Yes'
                }
            ]
        )
# Double check that there are no other instances without tags
for instance in inst_describe:
    if tag_to_check not in [t['Key'] for t in instance.tags]:
        print("Failed to assign tag, or new instance: ", instance.instance_id)        

The script is also available on GitHub here:
https://github.com/avansledright/awsTagCheck

If you find this script helpful feel free to share it with your friends and let me know in the comments!

Leave a Reply

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