Load EC2 Tags as Environment Variables in sixty seconds or less
Have you ever wanted to control your EC2 environment variables from AWS console? Well in a weird way you can. With a little scripting, you can load your EC2 tags as environment variables. This makes it pretty easy to control the configuration of your EC2 instance and the applications used.
The goal is to take all the tag name/value pairs and create export statements to load them as environment variables. So a tag with a name of "Environment" and value of "dev", would be parsed and made into
export Environement=dev
With the following script you can read in all of your EC2 tags and export them as environment variables automagically!
NOTE: Your EC2 instance will need the correct permissions to read the tags, so be sure to add the permissions to the role bound to your EC2. See the permissions required in the script.
This script worked fine (at first), however, I had some issues when there were spaces in the value field. It essentially only grabbed the value up to the first space. For example, a tag with the name of "Company" value of "Geek Cafe" would create an export of:
export Company=Geek
That's not the desired outcome.
So I modified the script to use awk. I'll be the first to admit that I'm not an awk expert, so if you see a better way to do this please let me know.