Last active
March 6, 2017 02:53
-
-
Save djravine/3dfd2d4580f1f31bdaa704b5d4bca583 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!
This file contains hidden or 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
###### | |
# Author: Marcello de Sales ([email protected]) | |
# Modifier: Adan Rehtla ([email protected]) | |
# Description: Create Create Environment Variables in EC2 Hosts from EC2 Host Tags | |
# Original GIST: https://gist.github.com/marcellodesales/a890b8ca240403187269 | |
# | |
### Requirements: | |
# * Install jq library (sudo apt-get install -y jq awscli) | |
# * 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=$(ec2metadata | grep instance-id | awk '{print $2}') | |
# Describe the tags of this instance | |
aws ec2 describe-tags --region sa-east-1 --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 'AWS_'$key | /usr/bin/tr '-' '_' | /usr/bin/tr ':' '_' | /usr/bin/tr '[:lower:]' '[:upper:]') | |
echo "$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
Update to Original GIST: https://gist.github.com/marcellodesales/a890b8ca240403187269