Skip to content
Advertisement

Cronjob script isn’t working as expected

I have a script that work perfectly fine when I manually run it by myself, but does not seem to run properly from crontab.

The main error is that the (external) environment variables are not being set.

I added SHELL=/bin/bash above the cronjob definition but still got the same errors.

The script I have copied and pasted below. Cheers for the help

#!/bin/bash
# export MYSQL_PORT_3306_TCP_ADDR=`awk 'NR==1 {print $1}' /etc/hosts`

set -e

MOUNT=/mnt/s3b/
BACKUP=/root/backups
mkdir -p $BACKUP
NOW=$(date +"%Y-%m-%d-%H%M")
DB_FILE="$MYSQL_ENV_MYSQL_DATABASE.$NOW.sql"

/usr/bin/s3fs <bucket_name> $MOUNT -ouse_cache=/tmp -odefault_acl=public-read -ononempty

mysqldump -h$MYSQL_PORT_3306_TCP_ADDR -uroot -p$MYSQL_ENV_MYSQL_ROOT_PASSWORD $MYSQL_ENV_MYSQL_DATABASE > /tmp/$DB_FILE

tar -czvf $BACKUP/"$DB_FILE.tar.gz" -P /tmp/$DB_FILE

cp $BACKUP/"$DB_FILE.tar.gz" $MOUNT/data/

The error as you can see below all the environment variables return:

 May 11 00:17:59 fcf074b9e5ee kernel: [293368.874868] SELinux: mount invalid.    Same superblock, different security settings for (dev mqueue, type mqueue)
 May 11 00:18:14 fcf074b9e5ee kernel: [293383.903080] docker0: port 6(veth2f6467f) entered forwarding state
 May 11 01:29:26 fcf074b9e5ee s3fs[78]: s3fs.cpp:s3fs_init(3334): init v1.79(commit:unknown) with OpenSSL
 May 11 01:29:26 fcf074b9e5ee s3fs[78]: s3fs.cpp:s3fs_check_service(3729):     Could not connect wrong region us-east-1, so retry to connect region eu-west-1.
 May 11 01:31:10 fcf074b9e5ee s3fs[93]: s3fs.cpp:s3fs_init(3334): init v1.79(commit:unknown) with OpenSSL
 May 11 01:31:10 fcf074b9e5ee s3fs[93]: s3fs.cpp:s3fs_check_service(3729): Could not connect wrong region us-east-1, so retry to connect region eu-west-1.
  May 11 10:25:02 fcf074b9e5ee kernel: [329791.913331] hrtimer: interrupt took 2331455 ns

  mysqldump -h -uroot -p > /tmp/.2016-05-11-0015.sql

Advertisement

Answer

As @that-other-guy pointed out, the environment variables $MYSQL_ENV_MYSQL_DATABASE, $MYSQL_ENV_MYSQL_ROOT_PASSWORD are not set.

Environment variables are inherited from process to children when a process forks. This means that the crontab jobs, will inherit the environment from the crontab service. Environment variables set in the shell when you install the crontab job, will not be preserved.

You should add in your shell script:

MYSQL_ENV_MYSQL_DATABASE="mydatabase"
MYSQL_ENV_MYSQL_ROOT_PASSWORD="mypassword"
Advertisement