I need to run a script as a user to backup my database every night. I added the following cron job in /etc/cron.d/backup-mysql via ansible.
0 3 * * * backup_mysql /path/backup-mysql.sh
I can see the job running in syslog :
Apr 29 03:00:01 myserver CRON[1534185]: (backup_mysql) CMD (/path/backup-mysql.sh)
However it does nothing and I don't understand why. I checked the path, run the script as the user. Everything works except when using this cron job.
The workaround I found is to replace the job with :
0 3 * * * root sudo -u backup_mysql /path/backup-mysql.sh
which works.
---------------------- EDIT 1 --------------------------
Following @Gerald Schneider advice in the comments, I checked the emails sent by cron yesterday during my tests :
From [email protected] Tue May 2 15:25:01 2023
Return-Path: <[email protected]>
Received: from myserver.com (localhost [127.0.0.1])
by myserver.com
for <[email protected]>; Tue, 2 May 2023 15:25:01 GMT
Received: (from backup_mysql@localhost)
by myserver.com
for backup_mysql; Tue, 2 May 2023 15:25:01 GMT
Date: Tue, 2 May 2023 15:25:01 GMT
Message-Id: <[email protected]>
From: [email protected] (Cron Daemon)
To: [email protected]
Subject: Cron <backup_mysql@myserver> /path/backup-mysql.sh
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/backup_mysql>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=backup_mysql>
backup-mysql.sh: Script can only be run as the "backup_mysql" user
The script seems to be run by a different user than backup_mysql. However, I specified the job to run as this user so I've no idea why it does not work.
Here's the part of the script that check the user :
backup_owner="backup_mysql"
sanity_check () {
# Check user running the script
if [ "$USER" != "$backup_owner" ]; then
error "Script can only be run as the \"$backup_owner\" user"
fi
...
}