Check Rails migration failure while deploying to Heroku with CircleCI.

6 Aug 2017

It's surprisingly non-trivial to detect the Rails migration failure during the deployment. The problem comes from the fact that git push doesn't exit with 1 if the migration fails. It took me a while to figure out a way to achieve what I want.

Note that we can tell Heroku to run Rails' migration while deploying by adding release: bundle exec rake db:migrate to Procfile. This even runs the migration on the new code before releasing to the users. This is superior than using git push and heroku run rake db:migrate. And, by the way, you can use heroku run rake db:migrate --exit-code to get the remote exit code.

Anyway, we can detect a deployment failure using heroku releases command. Here's a part of my circle.yaml:

deployment: staging: branch: develop commands: - | cat >~/.netrc <<EOF machine api.heroku.com login $HEROKU_EMAIL password $HEROKU_TOKEN machine git.heroku.com login $HEROKU_EMAIL password $HEROKU_TOKEN EOF - chmod 600 ~/.netrc # Heroku cli complains about permissions without this - "[[ ! -s \"$(git rev-parse --git-dir)/shallow\" ]] || git fetch --unshallow" - git push https://git.heroku.com/test-app.git $CIRCLE_SHA1:refs/heads/master -f # Check if the last release failed. Because Heroku doesn't exit an error code when # migration failed. - "! (heroku releases --app test-app -n 1 2>/dev/null | grep failed)"

I hope this helps with your deployment.