How to set an environment variable in Amazon EC2

PJ Bergeron picture PJ Bergeron · Feb 21, 2015 · Viewed 75k times · Source

I created a tag on the AWS console for one of my EC2 instances.

enter image description here

However, when I look on the server, no such environment variable is set.

The same thing works with elastic beanstalk. env shows the tags I created on the console.

$ env
 [...]
 DB_PORT=5432

How can I set environment variables in Amazon EC2?

Answer

Guy picture Guy · Feb 21, 2015

You can retrieve this information from the meta data and then run your own set environment commands.

You can get the instance-id from the meta data (see here for details: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-retrieval)

curl http://169.254.169.254/latest/meta-data/instance-id

Then you can call the describe-tags using the pre-installed AWS CLI (or install it on your AMI)

aws ec2 describe-tags --filters "Name=resource-id,Values=i-5f4e3d2a" "Name=Value,Values=DB_PORT"

Then you can use OS set environment variable command

export DB_PORT=/what/you/got/from/the/previous/call

You can run all that in your user-data script. See here for details: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html