How to run a cron job as a different user
Running cron jobs as another user is an advanced technique but one that is easy to master. This guide will take you beyond the comfort of crontab -e and show you how to use a system-wide crontab to schedule your job.
How to run a cron job as a different user?
To run a cron job as a different user, schedule the job in a system-wide crontab file, specifically by placing your own custom crontab file in /etc/cron.d, or adding your job to /etc/crontab. In a slight augmentation to the user crontab format, these system-wide crontabs have a user field after the schedule, and this will be used when the job is run. The field is required. It does not default to root. In this example, the backup runs once a day at midnight as the user dataproc:
$ cat /etc/cron.d/my-custom-crontab
0 0 * * * dataproc /var/cronitor/bin/database-backup.sh
The job's working directory is that user's home directory. See the crontab working directory. The five places a crontab can live are in where cron jobs are saved.
If you have just one or two jobs to schedule, it's quick and easy to just add them directly to /etc/crontab. If you have more jobs, it's better to organize them into their own crontab file and add it to the cron drop-in directory at /etc/cron.d. Either method usually requires root or sudo.
To edit /etc/crontab, open the file in your editor of choice. It looks like a user crontab, but sudo crontab -e edits the root user crontab, not /etc/crontab. That distinction matters when you want the job to run as someone other than root.
Want alerts if your cron jobs stop working?
Monitor your cron jobs with Cronitor to easily collect output, capture errors and alert you when something goes wrong.
Editing another user's crontab
Another way to run jobs as a different user is to add them directly to their user crontab. This functionality is built-in to the crontab command, and as an administrator you may sometimes wish to see or edit another user's crontab file, but it's not the recommended way to schedule and run jobs as different users. It's much easier to find and maintain jobs over time if these jobs are centralized at the system-wide locations outlined in the previous section.
That said, if you are absolutely sure you just want to add a job to another user's crontab, here's how you do it:
$ crontab -u <username> -e
CronitorCLI and the job's user
cronitor configure writes /etc/cronitor/cronitor.json owner-only (mode 0600). The user named on the cron line cannot read that file, so cronitor exec in their job has no API key. Set CRONITOR_API_KEY in the crontab to an SDK Integration key (a Telemetry key cannot create monitors), or point the job at a config file that user owns with CRONITOR_CONFIG. The details are in Using CronitorCLI.