How to Set Environment Variables on Ec2 Instance via User Data

AWS EC2 set environment variables

Your user data script is actually run. Nevertheless, it is run on its own bash process which dies at the end of your script.

Exported variables are preserved only for the lifetime of your script and they are also visible from child processes of your script.

Since new connections to your ec2 instance are not children of the original script that ran the user data, they don't inherit exported variables.

Set environment variables in an AWS instance

Using the export command only sets those variables for the current shell and all processes that start from that shell. It is not a persistent setting. Anything you wish to make permanent should be set in /etc/environment.

For example in userdata:

echo "JAVA_HOME=/jdk1.8.0_172" >> /etc/environment

This would add the JAVA_HOME=/jdk1.8.0_172 line to that file. Note, you should not use export inside that file.

The PATH variable is likely already defined in the /etc/environment file and you'll need to overwrite that appropriately if you are going to append additional paths to it.

There is really great details on setting environment variables available in this answer.

How to set an environment variable in Amazon EC2

Following the instructions given by Guy, I wrote a small shell script. This script uses AWS CLI and jq. It lets you import your AWS instance and AMI tags as shell environment variables.

I hope it can help a few people.

https://github.com/12moons/ec2-tags-env

Create file and persist environment variable via Amazon EC2 User Data script

The User Data script runs as the root user when the instance boots for the first time.

It is likely that there is no /files/ directory on the instance, so the file creation would fail. You should create that directory first.

The EXPORT probably won't work because the script is being run as root, whereas you will normally login as ec2-user. To persist an environment variable for a user, you would need to add it to a profile file.

See: How to permanently set environmental variables



Related Topics



Leave a reply



Submit