RVM and cron in production
UPDATED 6/7/2013 – We no longer recommend using bash -l -c to run Cron jobs with RVM. See our updated approach .
This info is for Scout users, but it’s also applicable to anyone who’s wondered how to use cron together with RVM. This assumes 1) you are using bash; 2) you running you cron tasks as a non-root user (say, “deploy”).
To use an RVM Ruby from cron, invoke your own bash session, like so:
* * * * * /bin/bash -l -c 'scout 8c6dc00d-af3a-4606-a384-...'
If you are editing root’s crontab, specify that the job is to be run by the deploy user:
* * * * * deploy /bin/bash -l -c 'scout 8c6dc00d-af3a-4606-a384-...'
/bin/bash -l -c Explained
We are wrapping our command (Scout in this case) in a bash session. The -c option tells bash a command follows. The -l option tells bash to load the entire environment. This option is crucial. Leave out the
-l and you’re in for some tedious debugging.
The wrapper is necessary because cron runs a very limited environment. RVM relies on environment variables to find Ruby, gems and gem executables (
env | grep rvm will show you RVM’s environmental additions).
bash -l brings all this into cron’s environment, so RVM just works. You don’t have to worry about PATH, gem executables, etc. They all work just like they do in your interactive bash sessions.
Important note: in most cases, you’ll want to use single quotes for the command you pass to bash.
Debugging cron tasks
Something not working? use this:
* * * * * /bin/bash -l -c 'scout 8c6dc00d-af3a-4606-a384-...' > /home/deploy/crondebug.log 2>&1
That last bit captures both normal and error output to a file. You can change the path it redirects to as needed.
What kind of RVM installation?
The RVM documentation suggests two kinds of RVM installation in production. You can install RVM systemwide as root, or for a particular user. The cron technique outlined above works for both kinds of RVM installations.
Which kind of RVM installation is best for you? It depends on your needs.
System-wide installation may be better if:
- You want your RVM Ruby in production to feel as much as possible like a “traditional” Ruby install.
- One person is both developer and sysadmin.
A User-specific installation is probably better if:
- You have multiple apps running under different users, and want to isolate each app’s environment as much as possible.
- You have a sysadmin who takes care of system health in general, but who wants to give Ruby developers maximum latitude with the Ruby installation.
See RVM’s instructions for system-wide install if you decide to go that route. Again, the format for cron outlined above works for either type of RVM install.