Categories
Amazon Web Services Cloud Architecting Python

Check EC2 Instance Tags on Launch

In my ever-growing quest to automate my AWS infrastructure deployments, I realized that just checking my tags wasn’t good enough. I should force myself to put tags in otherwise my instances won’t launch at all.

I find this particularly useful because I utilize AWS Backup to do automated snapshots nightly of all of my instances. If I don’t put the “Backup” tag onto my instance it will not be included in the rule. This concept of forced tagging could be utilized across many different applications including tagging for development, production, or testing environments.

To do this I created the Lambda function below. Utilizing EventBridge I have this function every time there is an EC2 instance that enters the “running” state.

import json
import boto3

def lambda_handler(event, context):
    detail = event['detail']
    ids = detail['instance-id']
    eventname = detail['state']
    ec2 = boto3.resource('ec2')
    
    while eventname == 'Running':
        print(ids)       
    #Check to see if backup tag is added to the instance
        tag_to_check = 'Backup'
        instance = ec2.Instance(ids)
        for tag in instance.tags:
            if tag_to_check not in [t['Key'] for t in instance.tags]:
                instance.stop()
                print("Stopping Instance: ", instance)
    #Get instance state to break the infinite loop
                state = instance.state['Name']          
                if state == "shutting-down":
                    print("instance is shutting-down")
                    break
                elif state == "stopped":
                    print("Instance is already stopped")
                    break
                elif state == "stopping":
                    print("instance is stopping")
                    break
        break
            

The function then will check the status of the instance to ensure that it is stopped and then break the loop.

You can clone the repository from GitHub here:
https://github.com/avansledright/aws-force-ec2-launch-tags

If you utilize the script please share it with your friends. Feel free to modify it as you please and let me know how it works for you! As always, if you have any questions feel free to reach out here or on any other platform!

Leave a Reply

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