Skip to content

Instantly share code, notes, and snippets.

@ormam
Last active July 2, 2022 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ormam/9de1eca73366bf0eb8cb44d06fd8fc7a to your computer and use it in GitHub Desktop.
Save ormam/9de1eca73366bf0eb8cb44d06fd8fc7a to your computer and use it in GitHub Desktop.
AWS auto tagging via Lambda
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)
@lokhandwalayusuf
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment