Voiced by Amazon Polly |
Overview
In cloud environments, visibility and accountability are everything. Without proper tagging of resources, organizations often struggle with cost allocation, compliance, and security posture. While AWS provides native tagging options, relying on manual processes is error-prone and inconsistent. This blog shows how you can automate resource tagging in real time using AWS CloudTrail and AWS Lambda, combined with user identity information from AWS IAM Identity Center (formerly AWS SSO).
This approach ensures that every newly created resource carries the correct metadata for ownership, department, or cost center without human intervention.
Pioneers in Cloud Consulting & Migration Services
- Reduced infrastructural costs
- Accelerated application deployment
Why Tagging Matters for Cost Governance?
Tags are key-value pairs you attach to AWS resources (e.g., Environment=Dev, Department=Finance). They enable:
- Cost Allocation: Chargeback and showback reports in AWS Cost Explorer depend on tags.
- Compliance: Enforcing mandatory tags ensures resources don’t go untracked.
- Automation: Policies like automated backups or lifecycle rules often rely on tags.
Without automation, it’s common to find hundreds of untagged resources, leading to wasted spend and compliance gaps.
Using AWS CloudTrail to Capture Resource Creation Events
AWS CloudTrail records all API actions across accounts. We’ll use it to detect when a resource is created and forward that event to a Lambda function.
For example, when a user launches an Amazon EC2 instance, AWS CloudTrail logs the RunInstances API call. This event can be captured by Amazon EventBridge (Amazon CloudWatch Events) and sent to an AWS Lambda function that applies tags automatically.
Command: Enable AWS CloudTrail if not already enabled
1 2 |
aws cloudtrail create-trail --name org-trail --s3-bucket-name my-cloudtrail-logs aws cloudtrail start-logging --name org-trail |
Deploying an AWS Lambda Function to Auto-Tag Resources
We will create an AWS Lambda function that:
- Listens to AWS CloudTrail events through Amazon EventBridge.
- Extracts the user identity (email/username) from the event.
- Fetches department details from AWS IAM Identity Center.
- Tags the created resource with details like Owner, Department, CreatedBy.
Python AWS Lambda code (simplified):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import boto3 import json org_client = boto3.client('identitystore') ec2 = boto3.client('ec2') IDENTITY_STORE_ID = "<your-identity-store-id>" def lambda_handler(event, context): print("Event:", json.dumps(event)) # Extract user identity user_identity = event['detail']['userIdentity'] username = user_identity.get('userName') or user_identity.get('principalId') # Lookup department in IAM Identity Center users = org_client.list_users(IdentityStoreId=IDENTITY_STORE_ID) department = "Unknown" for u in users['Users']: if u['UserName'] == username: for attr in u['Attributes']: if attr['AttributePath'] == "department": department = attr['AttributeValue'] # Extract resource ID (EC2 example) resource_id = event['detail']['responseElements']['instancesSet']['items'][0]['instanceId'] # Tagging the resource ec2.create_tags( Resources=[resource_id], Tags=[ {'Key': 'Owner', 'Value': username}, {'Key': 'Department', 'Value': department}, {'Key': 'CreatedBy', 'Value': 'AutoTagLambda'} ] ) return {"statusCode": 200, "body": "Resource tagged successfully"} |
Attach the AWS Lambda as the target:
1 2 3 |
aws events put-targets \ --rule EC2RunInstancesRule \ --targets "Id"="1","Arn"="arn:aws:lambda:ap-south-1:111122223333:function:AutoTagLambda" |
Fetching User Details from AWS IAM Identity Center
AWS IAM Identity Center acts as the single source of truth for user identities. We can fetch metadata such as department, email, or custom attributes using its Identity Store API.
Command: Get list of users
1 |
aws identitystore list-users --identity-store-id <store-id> |
This provides details like UserName, DisplayName, and custom attributes. These values can then be mapped to tags in your Lambda function.
Testing by Creating an Amazon EC2 Instance
To validate the automation:
- Launch an Amazon EC2 instance.
1 2 3 4 5 6 7 |
aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --count 1 \ --instance-type t2.micro \ --key-name mykey \ --security-group-ids sg-0123456789abcdef0 \ --subnet-id subnet-6e7f829e |
2. Wait for the AWS CloudTrail event to trigger the AWS Lambda.
3. Verify tags:
1 |
aws ec2 describe-tags --filters "Name=resource-id,Values=<instance-id>" |
Best Practices
- Define Tagging Standards: Agree on key tags such as Environment, Owner, CostCenter.
- Error Handling: Implement retries in the AWS Lambda if tagging fails due to API throttling.
- Cross-Account Setup: Deploy the AWS Lambda in each member account, but query the AWS IAM Identity Center from the management account.
- Logging: Send AWS Lambda logs to Amazon CloudWatch for auditing failed tagging attempts.
- Extensibility: Extend support beyond Amazon EC2, Amazon S3 buckets, Amazon RDS databases, and AWS IAM roles, which can also be auto-tagged.
Conclusion
Automating tagging with AWS CloudTrail, AWS Lambda, and AWS IAM Identity Center provides real-time, consistent governance across AWS accounts.
With this setup, every Amazon EC2, Amazon S3, or Amazon RDS resource created in your environment will carry the right metadata automatically.
Drop a query if you have any questions regarding Automating tagging and we will get back to you quickly.
Empowering organizations to become ‘data driven’ enterprises with our Cloud experts.
- Reduced infrastructure costs
- Timely data-driven decisions
About CloudThat
CloudThat is an award-winning company and the first in India to offer cloud training and consulting services worldwide. As a Microsoft Solutions Partner, AWS Advanced Tier Training Partner, and Google Cloud Platform Partner, CloudThat has empowered over 850,000 professionals through 600+ cloud certifications winning global recognition for its training excellence including 20 MCT Trainers in Microsoft’s Global Top 100 and an impressive 12 awards in the last 8 years. CloudThat specializes in Cloud Migration, Data Platforms, DevOps, IoT, and cutting-edge technologies like Gen AI & AI/ML. It has delivered over 500 consulting projects for 250+ organizations in 30+ countries as it continues to empower professionals and enterprises to thrive in the digital-first world.
FAQs
1. Can I tag resources created outside the AWS Console (e.g., via Terraform or CLI)?
ANS: – Yes. AWS CloudTrail captures all API calls made via Console, CLI, SDK, or Infrastructure as Code tools like Terraform.
2. What if a user creates a resource using an AWS IAM role instead of an individual identity?
ANS: – You can extract the role ARN from the AWS CloudTrail event and map it to the department or owner.
3. Does this automation add cost?
ANS: – AWS Lambda, AWS CloudTrail, and Amazon EventBridge are low-cost services. The main expense is AWS CloudTrail storage in Amazon S3, which is minimal compared to the governance benefits.

WRITTEN BY Rajveer Singh Chouhan
Rajveer works as a Cloud Engineer at CloudThat, specializing in designing, deploying, and managing scalable cloud infrastructure on AWS. He is skilled in various AWS services as well as automation tools like Terraform and CI/CD pipelines. With a strong understanding of cloud architecture best practices, Rajveer focuses on building secure, cost-effective, and highly available solutions. In his free time, he keeps up with the latest advancements in cloud technologies and enjoys exploring infrastructure automation and DevOps tools.
Comments