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

2 minute read
1

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

Short description

In Elastic Beanstalk, environment variables aren't exposed to the operating system (OS). When the environment variables are set as Elastic Beanstalk, you can use a utility with environment variables from the OS. To use a utility with Elastic Beanstalk environment variables, you must use an .ebextension that exports the environment variables to OS variables.

To use environment variables from an Elastic Beanstalk instance shell, complete the following steps:

  1. Use the get-config utility to read your Elastic Beanstalk environment variables.
  2. To transform the get-config output from JSON to shell variables, use the jq utility from the jq website.
  3. Save the variables on the /etc/profile.d/local.sh file. Bash reads this file to export variables to the OS.

Resolution

  1. Create an .ebextension file in your application source bundle, and then include the following information:
    commands:
        setvars:
            command: /opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "export \(.key)=\"\(.value)\""' > /etc/profile.d/local.sh
    packages:
        yum:
            jq: []
    Note: In the preceding example, the configuration file is named setvars.config.
  2. Save the .ebextension file, and then deploy it to your Elastic Beanstalk environment.
  3. To test if the .ebextension file exports the variables, use SSH to connect to your instance. Then, run the following command:
    env | grep VARIABLE_NAME
    Note: Set VARIABLE_NAME to a variable that's defined in your environment. Before you test, close all existing sessions. Then, use SSH to reconnect.

If your environment variables are correctly set, then your output looks similar to the following example. The RDS_PORT variable is defined in the Elastic Beanstalk environment.

$ env|grep RDS_PORTRDS_PORT=3306

Note: Because you use commands in the .ebextension, you can update only the local.sh file with a new deployment. If you add or change a variable in the environment, then create a new deployment before the variable is exported to the OS.

AWS OFFICIAL
AWS OFFICIALUpdated 2 months ago