Accessing environment variables in AWS Beanstalk ebextensions

ba0708 picture ba0708 · Apr 3, 2015 · Viewed 15.5k times · Source

I am trying to access an environment variable that I have defined in the AWS Beanstalk configuration. I need to access it within a config file in .ebextensions or in a file that is copied in place in a config file. I have tried the following:

container_commands:
  update_nginx_config:
    command: "cp .ebextensions/files/nginx/nginx.conf /etc/nginx/nginx.conf"

And in my nginx.conf file, I have tried to access $MYVAR, ${MYVAR} and {$MYVAR}, some of which was suggested here and here (the latter being directly within a config file).

files:
  "/etc/nginx/nginx.conf" :
    mode: "000644"
    owner: root
    group: root
    content: |
      $MYVAR ${MYVAR} {$MYVAR}

This does not work either. In all cases, the variable names are just output such as $MYVAR, so Beanstalk does not recognize my variables. I found the below in the AWS documentation about container_commands:

They also have access to environment variables such as your AWS security credentials.

This is great, but it does not say how.

How can I access an environment variable with ebextensions, be it within a config file itself or in a separate file that is copied in place?

Thank you in advance!

Answer

ba0708 picture ba0708 · Apr 10, 2015

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!