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 elifarley/2d8e4f74c0de98614a109d5fdc3a6b41 to your computer and use it in GitHub Desktop.
Save elifarley/2d8e4f74c0de98614a109d5fdc3a6b41 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: Marcello de Sales (marcello.desales@gmail.com)
# Description: Create Environment Variables in EC2 Hosts from EC2 Host Tags
#
### Requirements:
# * Install jq library (sudo apt-get install -y jq)
# * Install the EC2 Instance Metadata Query Tool (http://aws.amazon.com/code/1825)
#
### Installation:
# * Add the Policy EC2:DescribeTags to a User
# * aws configure
# * Souce 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 () {
# http://aws.amazon.com/code/1825 EC2 Instance Metadata Query Tool
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:')"
# Describe the tags of this instance
aws ec2 describe-tags --region "$EC2_REGION" --filters "Name=resource-id,Values=$INSTANCE_ID"
}
# Convert the tags to environment variables.
# Based on https://github.com/berpj/ec2-tags-env/pull/1
tags_to_env () {
tags=$1
for key in $(echo $tags | /usr/bin/jq -r ".[][].Key"); do
value=$(echo $tags | /usr/bin/jq -r ".[][] | select(.Key==\"$key\") | .Value")
key=$(echo $key | /usr/bin/tr '-' '_' | /usr/bin/tr '[:lower:]' '[:upper:]')
echo "Exporting $key=$value"
export $key="$value"
done
}
# Execute the commands
instanceTags=$(getInstanceTags)
tags_to_env "$instanceTags"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment