How to set Environment Variables on EC2 instance via User Data How to set Environment Variables on EC2 instance via User Data linux linux

How to set Environment Variables on EC2 instance via User Data


One of the more configurable approach to define environment variables for EC2 instances, is to use Systems Manager Parameter Store. This approach will make it easier to manage different parameters for large number of EC2 instances, both encrypted using AWS KMS as well as in plain text. It will also allows to change the parameter values with minimal changes in EC2 instance level. The steps are as follows.

  • Define string parameters (Encrypted with KMS or Unencrypted) in EC2 Systems Manager Parameter Store.
  • In the IAM role EC2 assumes, give required permission to access the parameter store.
  • Using the AWS CLI commands for EC2 System Manager, read the parameters and export to environment variables in User Data section using Get-Parameter or Get-Parameters AWS CLI commands and controlling command output as required.

e.g Using Get-Parameter command to retrieve db_connection_string parameter(Unencrypted).

export DB_CONNECTION=$(aws --region=us-east-2 ssm get-parameter --name 'db_connection' --query 'Value')

Note: For more details in setting up AWS KMS Keys, defining encrypted strings, managing IAM policies & etc., refer the following articles.


I find this to be a pretty easy way to set environment variables for all users using User Data. It allows me to configure applications so the same AMI can work with multiple scenarios:

#!/bin/bashecho export DB_CONNECTION="some DB connection" >> /etc/profileecho export DB_USERNAME="my user" >> /etc/profileecho export DB_PASSWORD="my password" >> /etc/profile

Now, all users will have DB_CONNECTION, DB_USERNAME and DB_PASSWORD set as environment variables.


The user data script on EC2 executes at after boot in its own process. The environment variables get set in that process and disappear when the process exits. You will not see the environment variables in other processes, i.e., login shell or other programs for that matter.

You will have to devise a way to get these environment variables into whatever program needs to see them.

Where do you need these variables to be available? In /startup.sh staging 2649?

EDIT

Try this:

#!/bin/bashset -e -x export HOST_URL="checkEmai-LoadBala-ICHJ82KG5C7P-2141709021.us-east-1.elb.amazonaws.com"/startup.sh staging 2649

Then edit /startup.sh, and put the following line on the top:

echo $HOST_URL > /tmp/var

Boot the instance, and then paste /tmp/var here.