Disable dangerous rake tasks in production
Yesterday, we had to restore the production DB from a backup, since we ran ârake db:schema:loadâ in production by mistake. To avoid that problem in the future, I decided to disable that task, and others than can screw with the DB, in production.Â
It was a matter of adding a prerequisite to those dangerous tasks, that checks if they are being run in production, and exit accordingly. I also added a flag to override this safeguard, together with some code to backup the DB. To do this, I added the following code to lib/tasks/disable_db_tasks_on_production.rake:
DISABLED_TASKS = [ âdb:dropâ, âdb:migrate:resetâ, âdb:schema:loadâ, âdb:seedâ,
âŚ
]
namespace :db do desc âDisable a task in production environmentâ task :guard_for_production do if Rails.env.production? if ENV[âI_KNOW_THIS_MAY_SCREW_THE_DBâ] != â1â puts âThis task is disabled in production.â puts âIf you really want to run it, call it again with `I_KNOW_THIS_MAY_SCREW_THE_DB=1`â exit else require âherokuâ puts âMaking a backup of the database, just in caseâŚâ puts `heroku pgbackups:capture` end end end end
DISABLED_TASKS.each do |task| Rake::Task[task].enhance [âdb:guard_for_productionâ] end
It would be nice to add something like this to the default Rails app, since, if you are reading this, chances are high that is too late for this to protect you by now :)
Some feedback from redditâs darkphnx, nice to know weâre not the only ones :)
Initially you think âWhat sort of moron would write db:schema:loadâ on a production machine, but itâs not that simple.Â
Plenty of application hosting systems will look at what sort of application youâre deploying and make assumptions about what commands should be run on first deployment. Very often one of these is ârake db:schema:loadâ.Letâs say youâre deploying to a new hosting environment, but pointing to an existing database. If you forget to check what commands are going to run on first deployment deployment it will come along and be very helpful âoh, this is the first time youâve deployed this app, Iâll load the database schema for youâ. db:schema:load drops any existing tables.If youâre not watching the deployment carefully, the first time youâll know is when the deployment is complete all your data is gone. If youâre lucky you were watching and youâve only lost a couple of tables.Source: Did exactly this, had to restore a 50GB table from backup.
