AWS Elastic Beanstalk上Rails生产控制台无法读取环境变量问题求助
I’ve run into this exact headache with Elastic Beanstalk and Rails console access before—let’s break down why this happens and how to fix it:
The Core Issue
AWS Elastic Beanstalk keeps your environment variables stored in a managed system, but they don’t automatically load into your raw SSH shell session when you log in. Your Rails app can access these variables during deployment because EB injects them into the app’s runtime environment, but the basic SSH session doesn’t inherit them by default. That’s why erb config/database.yml shows empty values and your console can’t authenticate with Postgres.
Step-by-Step Fix
Load EB’s environment variables into your current shell
Right after SSH’ing into your EC2 instance, run this command to pull in all the environment variables you set in the EB console:source /opt/elasticbeanstalk/support/envvarsVerify the variables loaded correctly by running:
env | grep RDS_You should see
RDS_PASSWORD,RDS_USERNAME, and other database-related variables printed with their correct values.Launch the Rails production console
Now that your shell has access to the required env vars, start the console normally:bundle exec rails c productionQueries like
Wager.allshould run without the password error now.
Bonus: Clean Up Your database.yml
Hardcoding the host and port isn’t ideal—using EB’s environment variables is more maintainable (and avoids issues if your RDS endpoint changes later). Update your production config to rely fully on the env vars:
production: <<: *default url: <%= ENV['DATABASE_URL'] %> # Alternatively, if you prefer explicit fields over the URL: # database: <%= ENV['RDS_DB_NAME'] %> # username: <%= ENV['RDS_USERNAME'] %> # password: <%= ENV['RDS_PASSWORD'] %> # host: <%= ENV['RDS_HOSTNAME'] %> # port: <%= ENV['RDS_PORT'] %>
Since you confirmed /opt/elasticbeanstalk/bin/get-config environment returns the correct values, sourcing the envvars script will make all these variables available to Rails.
Quick Note About User Switching
If you need to switch to the app user (like sudo su - webapp), make sure to preserve environment variables with the -E flag:
sudo -E su - webapp source /opt/elasticbeanstalk/support/envvars bundle exec rails c production
Without -E, the env vars won’t carry over to the new user session, and you’ll hit the same password issue.
内容的提问来源于stack exchange,提问作者Kevin Sun

