Accessing environment variables in AWS Beanstalk ebextensions

I reached out to the Amazon technical support for an answer to this question, and here is their reply:


Unfortunately the variables are not available in ebextensions directly. The best option to do that is by creating a script that then is run from container commands like this:

files:
  "/home/ec2-user/setup.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/bash

      # Commands that will be run on container_commmands
      # Here the container variables will be visible as environment variables.

container_commands:
  set_up:
    command: /home/ec2-user/setup.sh

So, if you create a shell script and invoke it via a container command, then you will have access to environment variables within your shell script as follows: $ENVIRONMENT_VARIABLE. I have tested this, and it works.

If you're having issues running a script as root and not being able to read the configured environment variables, try adding the following to the top of your script.

. /opt/elasticbeanstalk/support/envvars

Depending on your use case, you might have to change your approach a bit (at least I did), but it is a working solution. I hope this helps someone!


From this answer: https://stackoverflow.com/a/47817647/2246559

You can use the GetOptionSetting function described here: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions-functions.html

For instance, if you were setting the worker_processes variable, it could look like:

files:
  "/etc/nginx/nginx.conf" :
    mode: "000644"
    owner: root
    group: root
    content: |
      worker_processes `{"Fn::GetOptionSetting": {"Namespace": "aws:elasticbeanstalk:application:environment", "OptionName": "MYVAR"}}`;

Note the backticks `` in the function call.


In case you're using the value directly in a container command, the get-config script that comes with the instance can help.

Example :

20_install_certs:
  command: |
    MY_VAR=$(/opt/elasticbeanstalk/bin/get-config environment -k MY_VAR)