For Amazon Linux 2 you need to export your Elastic Beanstalk variables to the shell profile so that they can be used to invoke your rails
command from inside the /var/app/current
directory.
This approach might look scary to some of you, but it's really nothing special. Basically the root-protected /etc/profile.d/sh.local
file will contain all of your Elastic Beanstalk environment's variables. This includes passwords and master keys ... lots of sensitive stuff. If a bad guy (or girl or bot) compromises your app by somehow ssh'ing into your Elastic Beanstalk instance, they WILL be able mess with your app. If that terrifies you, stop reading. If you still want to run your rails tasks or console from inside your Elastic Beanstalk instance, read on ...
The modern Amazon Linux 2 way to accomplish this is to create a prebuild hook file that will write all the Elastic Beanstalk environment variables to /etc/profile.d/sh.local
. This way when you eb ssh <YOUR-ENVIRONMENT-NAME>
into your Elastic Beanstalk instance, all of the Elastic Beanstalk variables will be included in YOUR shell session.
In your Rails app, create a new script file precisely at: <YOUR_RAILS_APP_ROOT>/.platform/hooks/prebuild/set-vars.sh
. The file's will be:
#!/bin/bash
# put envars into /etc/profile.d/sh.local so that they an be used to `bundle exec rails c`
# see https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-env-variables-shell/
# installs `jq` to transform the json representation of the env vars
# into shell-happy looking env-vars
yum install -y jq
# write your eb environment variables to /etc/profile.d/sh.local
/opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "export \(.key)=\"\(.value)\""' > /etc/profile.d/sh.local
Commit this file to your project and deploy your application to Elastic Beanstalk.
Once the deployment has successfully concluded, ssh into your Elastic Beanstalk instance and try to run some rails commands from your application directory:
$ eb ssh <YOUR-ENVIRONMENT-NAME>
_____ _ _ _ ____ _ _ _
| ____| | __ ___| |_(_) ___| __ ) ___ __ _ _ __ ___| |_ __ _| | | __
| _| | |/ _ \/ __| __| |/ __| _ \ / _ \/ _\ | '_ \/ __| __/ _\ | | |/ /
| |___| | (_| \__ \ |_| | (__| |_) | __/ (_| | | | \__ \ || (_| | | <
|_____|_|\__,_|___/\__|_|\___|____/ \___|\__,_|_| |_|___/\__\__,_|_|_|\_\
Amazon Linux 2 AMI
$ cd /var/app/current
$ bundle exec rails --version
Rails 7.#.#
$ bundle exec rails -T
rails about # List versions of all Rails frameworks and the environment
...
$ bundle exec rails c
Loading ... environment (Rails 7.#.#)
irb(main):001:0>
Inspiration came from: https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-env-variables-shell/
Learn extending Linux 2 Elastic Beanstalk docs here: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html
...press the up arrow, mark as modern answer/solution so the rest of us can find this...