Automatically tag EC2 instances with OS

I was surprised that a blog post doesn’t already exist (or at least I didn’t find one), so, this post covers how to automatically add a tag to EC2 instances upon creation with OS of the instance. After the below components are deployed, EC2 instances should automatically have either a os:linux or os:windows tag.

  1. First, create a Lambda function with the following code. I called my function autoTagEC2OS. Use Python 3.12:

import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    instances = ec2.describe_instances()
    
    for reservation in instances['Reservations']:
        for instance in reservation['Instances']:
            os_tag = 'unknown'
            for tag in instance.get('Tags', []):
                if tag['Key'] == 'os':
                    os_tag = tag['Value']
                    break
            if os_tag == 'unknown':
                # Determine the OS and tag the instance
                platform = instance.get('Platform', 'linux')
                if platform == 'windows':
                    os_value = 'windows'
                else:
                    os_value = 'linux'
                
                ec2.create_tags(
                    Resources=[instance['InstanceId']],
                    Tags=[{'Key': 'os', 'Value': os_value}]
                )

2. Next, in the Lambda function, go to Configuration, Permissions, and the click on the Role name. It would have a name something like autoTagEC2OS-role-XXXXXXXX. Click Add permissions and then “Create inline policy“. Add the following code, name it something like “DescribeEC2andAddTag”. (Thank you Automatically Tag AWS EC2 Instances and Volumes | DoiT for this part)

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Sid": "VisualEditor0",
			"Effect": "Allow",
			"Action": "ec2:CreateTags",
			"Resource": [
				"arn:aws:ec2:*:*:instance/*",
				"arn:aws:ec2:*:*:volume/*"
			]
		},
		{
			"Sid": "VisualEditor1",
			"Effect": "Allow",
			"Action": [
				"ec2:DescribeInstances",
				"ec2:DescribeVolumes"
			],
			"Resource": "*"
		}
	]
}

3. Go to EventBridge, and create a new rule, I called mine autoTagEC2OS-event. Choose “Rule with an event pattern“. Choose “Custom pattern (JSON editor)“. Enter the following code and click Next:

{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": {
    "state": ["running", "pending"]
  }
}

4. Choose the following parameters.
Target types: AWS Service
Select a target: Lambda function
Function: autoTagEC2OS

5. Choose Next, Next and then Create Rule

Now when you create a new EC2 instance, it should automatically have either a os:linux or os:windows tag.

Leave a comment

Blog at WordPress.com.

Up ↑