如何在 AWS Elastic Beanstalk 上为 Rails 应用程序播种数据库

How do I seed a database for Rails app on AWS Elastic Beanstalk

我在本地构建了一个小型 Rails 应用程序并尝试将其部署到 AWS Elastic Beanstalk。

这是我一直关注的指南:

http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Ruby_rails.html

部署成功,但没有进行数据库播种,所以我的所有静态列表值都是空的。

虽然我认为这不是 "ideal" 解决方案,但我确实尝试通过 SSH 连接到 EB 实例来手动为数据库做种。

eb ssh
cd /var/app/current/
rake db:seed

然后结果是:

[ec2-user@ip-172-31-13-16 current]$ rake db:seed
Rails Error: Unable to access log file. Please ensure that /var/app/current/log/production.log exists and is writable (ie, make it writable for user and group: chmod 0664 /var/app/current/log/production.log). The log level has been raised to WARN and the output directed to STDERR until the problem is fixed.
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
   (0.1ms)  begin transaction

 ...

(0.1ms)  rollback transaction
rake aborted!
ActiveRecord::StatementInvalid: SQLite3::ReadOnlyException: attempt to write a readonly database: INSERT INTO "users" ("first_name", "last_name", "email", "encrypted_password", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?)
/var/app/current/db/seeds.rb:9:in `<top (required)>'
SQLite3::ReadOnlyException: attempt to write a readonly database
/var/app/current/db/seeds.rb:9:in `<top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

执行此操作的正确方法是什么?

提前致谢!

试试看 RAILS_ENV=production bundle exec rake db:seed

它在当前包的上下文中使用命令 db:seed 执行 rake 脚本。

两个错误(Unable to access log fileattempt to write a readonly database)都是由于文件访问权限引起的。

当您通过 ssh 连接到 EC2 实例时,您通常以对 capistrano 部署目录没有写入权限的用户身份登录。 (您具有读取权限,因此您可以查看文件,但不能写入 - 因此您无法写入日志或创建新的 sqlite 数据库文件)。

您可以使用 sudo 来 运行 作为另一个用户进行抽取:

sudo -u app env PATH=$PATH RAILS_ENV=production bundle exec rake db:seed

(将“-u app”更改为您的应用 运行 的任何用户名 - 或者将其保留为 运行 作为 root 的命令)

如果您在此处并且上述解决方案对您不起作用。

除了使用 benchwarmer 上面这个答案中提供的命令外:

我必须 运行 种子命令为主密钥和所有 rds 设置提供环境变量。

bundle exec rake db:seed RAILS_ENV=production RAILS_MASTER_KEY=<your master key> RDS_HOSTNAME=<your rds hostname> RDS_PASSWORD=<...> RDS_USERNAME=<...> RDS_DB_NAME=<...> RDS_PORT=<...>

终于成功了:)

您可以在 AWS 控制台(仪表板)的环境配置面板中检查所有这些。