Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save specialorange/39957a8c889c49b860adf6db9f2fe871 to your computer and use it in GitHub Desktop.
Save specialorange/39957a8c889c49b860adf6db9f2fe871 to your computer and use it in GitHub Desktop.
Create Environment Variables in EC2 Hosts from EC2 Host Tags, just like Beanstalk or Heroku does!
######
# Author: Chris Frisina from Marcello de Sales (marcello.desales@gmail.com)
# Description: Create Environment Variables in EC2 Hosts from EC2 Host Tags
#
### Requirements:
#
### Installation:
# * Add the Policy EC2:DescribeTags to a User (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-ec2-console.html)
# * aws configure
# * Source it to the user's ~/.profile that has permissions
####
# Add tags to an EC2 host or Image Profile
# Reboot and verify the result of $(env).
# Loads the Tags from the current instance
getInstanceTags () {
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
# Print tags as 'export TAG_Key="Value"'
aws ec2 describe-tags --region $EC2_REGION --filters "Name=resource-id,Values=$INSTANCE_ID" | \
python -c "import sys,json; map(lambda t: sys.stdout.write('export TAG_%s=\"%s\"\n' % (t['Key'], t['Value'])), json.load(sys.stdin)['Tags'])"
}
# Export variables from tags
$(getInstanceTags)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment