Search code examples
bashcronamazon-cloudwatch

Why doesn't cron successfully run my bash script


I have a cron job listed in the root user's crontab:

*/5 * * * * /usr/local/bin/service_monitor.sh

The contents of the file are below:

#!/usr/bin/bash -e


/usr/bin/systemctl is-active --quiet nginx && aws cloudwatch put-metric-data --metric-name hearbeat-nginx --namespace heartbeat --value 1 --region eu-west-1
/usr/bin/systemctl is-active --quiet prosody && aws cloudwatch put-metric-data --metric-name heartbeat-prosody --namespace hearbeat --value 1 --region eu-west-1

The file is executable and when I run it directly as root it runs with no issues and I get the metric recorded in AWS CloudWatch so I know there is no issues with the AWS cli or permissions. However, when I try to run it as a cron job I don't see any metrics created. I can see the file is being executed by cron in the syslogs. Any ideas?


Solution

  • aws may not be on the PATH passed to the environment of this program. As a best practice, consider either

    • always referencing executables by absolute path in cron configuration files (easy to test) or
    • always setting your PATH explicitly (more readable).

    Also, you have a typo hearbeat.