Blog

Elastic Beanstalk custom environment variables

Why use environment variables

When developing an application some times you want to use different configuration values between development, staging/testing, and production environments. Many modern frameworks provide easy ways to set different configurations based on what environment you are using. Further more there may be instances when you want to use API keys, secret, SMTP username/passwords, etc, that you want to keep secret and not commit to the repository. One common solution to address this problem is to set environment variables.

How to set environment variables?

There are different ways to set these variables. Using Apache, for example, if you have mod_env you can set an environment variable using the SetEnv directive in your .htaccess. Using PHP you could set it by using the putenv function, these can be placed in a config file that gets included on every request. In a PHP application you will access these values via the $_SERVER super global or the getenv function.

Up until now it is still not clear how we are going to keep the value of the variables separate from our code. Elastic Beanstalk provides by default 5 environment variables called PARAM1-5 that can be set through the AWS Console under Environment Details -> Edit Config -> Container

Five values can be limiting or you may want to use more meaningful names such as DB_USERNAME and DB_PASSWORD. In order to add your own custom values you need to use ebextension config files.

First create a directory at the root of your project called .ebextensions/. Then create a file in .ebextensions/ called environment.config (this file can be called anything but it must have the .config extension) and add the following values


option_settings:
  - option_name: CUSTOM_ENV
    value: staging
    

After the application has been deployed you will see the new value under Environment Details -> Edit Configuration -> Container. To prevent committing values to your repository like API keys, secrets and so on, you can put a placeholder value.

    
option_settings:
  - option_name: SOME_API_KEY
    value: placeholder-value-change-me
    

You can update the values in the AWS console. After the values have been updated in the console for the first time, changing the config file and deploying WILL NOT update the values in the application..

References

  1. AWS ebextension config files
  2. How do you pass environment variable on Amazon Elastic Beanstalk PHP?
  3. PHP getenv
  4. SetEnv Directive