How to write a shell command in the Procfile to copy a database from production to staging on Heroku?

Viewed 70

I would like to use curl and the Heroku API to copy the database from PRODUCTION to STAGING. I am using the below at the moment :

release-task.sh

echo "Beginning workflow specific to STAGING"
echo "Turning off the web dynos.";
curl -X PATCH https://api.heroku.com/apps/${app_name_or_id} \
    -d "{\"maintenance\": true }" \
    -H "Content-Type: application/json" \
    -H "Accept: application/vnd.heroku+json; version=3" \
    -H "Authorization: Bearer $HEROKU_API_KEY"

echo "Copying from production database to staging database ...";
"""MISSING CODE HERE"""
    
echo "Turning the staging server back on.";
curl -X PATCH https://api.heroku.com/apps/${app_name_or_id} \
    -d "{\"maintenance\": false }" \
    -H "Content-Type: application/json" \
    -H "Accept: application/vnd.heroku+json; version=3" \
        -H "Authorization: Bearer $HEROKU_API_KEY"

Would anyone know how to do it, please?

1 Answers

Heroku provides a basic function via their CLI to do exactly that: https://devcenter.heroku.com/articles/heroku-postgres-backups#direct-database-to-database-copies

I did something like this with success, without the need for a complicated cURL command:

if [[ -n "$REVIEW_APP" ]]; then
  if rake db:version | grep -q "Current version: 0"; then
    heroku pg:copy application_name::DATABASE_URL DATABASE_URL -a "$HEROKU_APP_NAME" --confirm "$HEROKU_APP_NAME"
  fi

Obviously, this is for a rails app (given the rake db:version), but that is just to safeguard from accidentally deleting data. The meat of the command comes from:

heroku pg:copy application_name::DATABASE_URL DATABASE_URL -a "$HEROKU_APP_NAME" --confirm "$HEROKU_APP_NAME"

Just need to setup your ENV variables for the DATABASE_URL in the heroku config vars section of your app's settings.

If you can't execute the .sh file, don't forget to give it executable permissions in the command line: chmod +x filename.sh

Related