Last active
March 20, 2025 20:12
-
-
Save ormam/9de1eca73366bf0eb8cb44d06fd8fc7a to your computer and use it in GitHub Desktop.
AWS auto tagging via Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def lambda_handler(event, context): | |
#-------------------- Debug --------------------------- | |
#print( 'Hello {}'.format(event)) | |
#print( 'User Name- {}'.format(event['detail']['userIdentity']['principalId'])) | |
#print( 'Instance ID- {}'.format(event['detail']['responseElements']['instancesSet']['items'][0]['instanceId'])) | |
# Variables | |
instanceId = event['detail']['responseElements']['instancesSet']['items'][0]['instanceId'] | |
userNameSTring = event['detail']['userIdentity']['principalId'] | |
# Checks if the user is an okta user | |
if ":" in userNameSTring: | |
userName = userNameSTring.split(":")[1] | |
else: | |
userName = event['detail']['userIdentity']['userName'] | |
print( 'Instance Id - ' , instanceId) | |
print( 'User Name - ' , userName) | |
tagKey = 'owner' | |
tagValue = userName | |
# ---------------------- Body ---------------------- | |
# EC2 tagging | |
client = boto3.client('ec2') | |
response = client.create_tags( | |
Resources=[ | |
instanceId | |
], | |
Tags=[ | |
{ | |
'Key': tagKey, | |
'Value': tagValue | |
}, | |
] | |
) | |
# Volume tagging | |
ec2 = boto3.resource('ec2') | |
instance = ec2.Instance(instanceId) | |
volumes = instance.volumes.all() | |
for volume in volumes: | |
volID = volume.id | |
print("volume - " , volID) | |
volume = ec2.Volume(volID) | |
tag = volume.create_tags( | |
Tags=[ | |
{ | |
'Key': tagKey, | |
'Value': tagValue | |
}, | |
] | |
) | |
print(response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this code. I was just looking for something like this. But i have a query if you can help me.
Instead of single Key/Value, I need to update 3 different Key/Value. Would you be able to help me where in this code should i update so that it creates 3 different Key/Values.
Thanks in advance