How do I use environment variables from an Elastic Beanstalk instance shell?
Last updated: 2021-08-25
I want to use environment variables from an AWS Elastic Beanstalk instance shell.
In Elastic Beanstalk, environment variables aren't exposed to the operating system.
To use a utility with environment variables from the operating system when the environment variables are set as Elastic Beanstalk environment variables, you must use a .ebextension that exports the environment variables to operating system variables.
The following resolution shows you how to:
1. Use the get-config utility to read your Elastic Beanstalk environment variables.
2. Use the jq utility (from the jq website) to transform the get-config output from JSON to shell variables.
3. Save the variables on the /etc/profile.d/sh.local file. This file is read by Bash to export variables to the operating system.
1. Create a .ebextension file in your application source bundle and include the following:
commands: setvars: command: /opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | . | "export \(.key)=\"\(.value)\""' > /etc/profile.d/sh.local packages: yum: jq: 
Note: The configuration file in step 1 is called setvars.config.
2. Save the .ebextension file, and then deploy it to your Elastic Beanstalk environment.
3. To test if the variables are being exported, connect to your instance using SSH, and then run the following command. Before testing, close any existing sessions and then reconnect using SSH.
env | grep VARIABLE_NAME
Important: For step 3, set VARIABLE_NAME to a variable defined in your environment.
The output shows if your environment variables are set correctly. In the following example output, a variable called RDS_PORT is defined in the Elastic Beanstalk environment.
$ env|grep RDS_PORT RDS_PORT=3306
Note: Because you're using the commands on the .ebextension, you can update the sh.local file only with a new deployment. If you add or change a variable in the environment, then you must create a new deployment before the variable is exported to the operating system.