How do I use environment variables from an Elastic Beanstalk instance shell?

Last updated: 2020-10-20

I want to use environment variables from an AWS Elastic Beanstalk instance shell.

Short description

In Elastic Beanstalk, environment variables are not exposed to the operating system.

If you want to use a utility with environment variables from the operating system and the environment variables are set as Elastic Beanstalk environment variables, then 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 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.

Resolution

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 deploy it to your Elastic Beanstalk environment.

3.    To test if the variables are being exported, connect to your instance using SSH, then run the following command.

env | grep VARIABLE_NAME

Important: For step 3, change VARIABLE_NAME for one of the variables that you 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 only update the sh.local file with a new deployment. If you add or change a new variable in the environment, then you must create a new deployment before the variable is exported to the operating system.


Did this article help?


Do you need billing or technical support?