failure snippets

Notifications for failing cron jobs

Tagged cron, failure, notification, slack  Languages bash

Here’s a simple way of receiving a notification to a Slack channel when a cron job fails:

#!/usr/bin/env sh

# Replace this with the command
echo "hello world" &> /var/log/app.log

if [ $? -eq 0 ]
  curl -X POST -H 'Content-Type: application/json' --data "{\"text\":\"Cron job ran successfully $(tail -n 5 /var/log/app.log)\"}" $SLACK_URL
  exit 0
  curl -X POST -H 'Content-Type: application/json' --data "{\"text\":\"Cron job failed $(tail -n 5 /var/log/app.log)\"}" $SLACK_URL
  exit 1

Set the SLACK_URL environment variable to your slack channel’s hook URL.

A message will be sent to the Slack channel whenever the command fails along with the last 5 lines from the log file.