Have you ever needed to run a rake task (or any other comand for that matter) on a deployed instance but then realized you didn't have the the required environment variables loaded into your shell?
Here's a short shell script to the rescue:
#!/bin/bash /opt/elasticbeanstalk/bin/get-config --output YAML environment | sed 's/\: /\=/' | sed 's/^/export /' > /var/app/current/.env source /var/app/current/.env "[email protected]"
You can save this file into your Rails app's
bin directory as
appenv and then mark it as executable with
chmod +x bin/appenv.
This script relies on a built-in AWS Elastic Beanstalk command to retrieve the environment variables and we simply do some string manupulation to get it in a way that a shell can interpret it directly.
Running this script creates a
.env file that you can use in other shell scripts or you can simply call this bash script directly with the command and arguments you need like so:
[/var/app/current]$ bin/appenv rake db:version
The command will execute with all environment variables loaded (such as
RAILS_ENV=production and connect to the database properly.