AWS Elastic Beanstalk - Dump Environment Variables to .env File
This is a short guide how to use .env
files easily with AWS Beanstalk.
Background
I've been testing AWS Elastic Beanstalk for a PHP app that's loosely built on Symfony components. I've been using Beanstalk for some simple apps, but this is a bit more complex and I ran into trouble with defining environment variables and accessing them from both web and the console.
Why Environment Variables?
Almost all apps need some kind of configuration variables for the different environments where your application runs in. For example, your local development machine has different database credentials than your production environment.
These credentials need to be accessible from code, but they should not live in your codebase. This is exactly what environment variables are for. They are related to the environment where your code is running.
Environment Variables in AWS Elastic Beanstalk
Elastic Beanstalk has a simple UI for managing environment variables. This is the perfect place for things like database settings or defining paths for data folders.
All the variables defined in the console will be available in your web app.
Dumping the Variables into an .env file
For most cases using Symfony and PHP defining the variables in the AWS Beanstalk console is usually enough. I had a slightly different use case where I'm also running some command line scripts inside the same container.
For some reason the environment variables are not available if you're running a command line script on the instance. My solution was to just dump all the variables into an .env
file and load that file in my command line script.
Luckily, this was quite easy after a few tries and errors.
Define a Post Deploy Script
Elastic Beanstalk has multiple ways to modify the environment where the application runs. I used postdeploy hooks to dump the environment variables. Here's the script:
// .platform/hooks/postdeploy/01-dump-dot-env.sh
#!/bin/bash
/opt/elasticbeanstalk/bin/get-config --output YAML environment | sed -r 's/: /=/' > /var/www/html/.env
Notice, that all the hook scripts need to be executable, so remember to chmod a+x
that file.
The get-config
command is an internal tool provided by AWS, that will output all the environment variables. In this case, I'm fetching them in yaml format. The sed
command just replaces all the :
in the yaml file with =
. That's the usual format for .env
files.
And the last bit > /var/www/html/.env
just outputs all of that into a file called /var/www/html/.env
. That's where my application reads the env variables from.
Conclusions and Next Steps
And that's it! It's pretty simple and it works, but I think there's some room for improvement.
From a performance perspective it might be useful to dump the file contents into a php file. Symfony already has some scripts to automate this, but I'll need to look into this in more detail.
Last updated at August 22, 2023