How to run rake db:seed in Amazon Elastic Beanstalk


AllCloud Blog:
Cloud Insights and Innovation

Once bundle install is completed, Elastic Beanstalk runs a set of rake jobs when deploying a Ruby on Rails application, such as  asset compilation and database migration .

These jobs run pre-deployment , via a set of command hooks executed in alphabetical order, while the application has not yet reached its final resting place, which is /var/app/current/ .

Apart from these default ones , you may want to call additional tasks, as for e.g.  database seeding , or index creation , etc. In this case , rather than creating container commands that will run post-deployment, you can add your custom  hooks  to the pre-deployment sequence and run your jobs immediately after  db:migration .

Here’s an example on how to create such a task for db seeding:

In the root of your .ebextensions directory add a config file , let’s name it db_seed.config . In it add the following content :

files:
  "/opt/elasticbeanstalk/hooks/appdeploy/pre/13_db_seed.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      . /opt/elasticbeanstalk/support/envvars
      cd $EB_CONFIG_APP_ONDECK
      su -c "leader_only rake db:seed" $EB_CONFIG_APP_USER ||
      echo "Rake task failed to run, skipping seeding."
      true

This will create the script that runs db:seed and it will ensure it runs after db:migration (which is called via 12_db_migration.sh in the pre-deployment sequence ) . It also makes sure seeding is performed only once, from the instance Elastic Beanstalk has elected as leader within the auto-scale group, instead of running from all instances at the same time. Possible by setting the leader_only flag to “true” when issuing the rake command.

Lahav Savir

Founder and CTO, Cloud Platforms

Read more posts by Lahav Savir