Skip to content

Instantly share code, notes, and snippets.

@jaygooby
Last active April 12, 2017 12:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaygooby/e6189a42bed234b4e458755db6112502 to your computer and use it in GitHub Desktop.
Save jaygooby/e6189a42bed234b4e458755db6112502 to your computer and use it in GitHub Desktop.
Pipe your Monit email alerts into Slack
#!/bin/bash
# Save this file as e.g. /usr/local/bin/monit-alert-slack.sh
# then chmod +x /usr/local/bin/monit-alert-slack.sh
#
# In your /etc/monitrc set a user to get the alerts you
# want pushed to Slack:
#
# set alert monit-alerts@localhost
#
# and then in /etc/aliases set this as the user which
# this script is piped to:
#
# monit-alerts: |/usr/local/bin/monit-alert-slack.sh
#
# Then run newliases
#
# You'll need to ensure that e.g. exim has been configured to allow
# the pipe transport, otherwise the /etc/aliases config will be ignored
#
# SYSTEM_ALIASES_PIPE_TRANSPORT = address_pipe
#
#
# Dependencies: curl & formail
#
# Jay Caines-Gooby
# jay@gooby.org
# @jaygooby on Twitter
while read email
do
case "$email" in
Date:*)
# the pipe to xargs removes leading and trailing whitespace
MONIT_DATE=$(echo "${email}" | cut -d":" -f2- | xargs)
;;
Subject:*)
case "$email" in
*succeeded* | *Exists*)
SLACK_COLOUR=good
;;
*matched* | *failed* | *Does*not*exist*)
SLACK_COLOUR=danger
;;
*)
SLACK_COLOUR=warning
;;
esac
MONIT_SUBJECT=$(echo "${email}" | cut -d":" -f2- | xargs)
;;
*)
if [ -z "$MONIT_BODY" ]; then
MONIT_BODY="$email"
else
MONIT_BODY="${MONIT_BODY}\n${email}"
fi
;;
esac
done < <(formail -k -X Subject: -X Date:)
echo SLACK_COLOUR is $SLACK_COLOUR
/usr/bin/curl \
-X POST \
-s \
--data-urlencode "payload={ \
\"channel\": \"#server-chatter\", \
\"username\": \"Monit\", \
\"pretext\": \"$MONIT_DATE | $MONIT_SUBJECT\", \
\"color\": \"$SLACK_COLOUR\", \
\"icon_emoji\": \":eyes:\", \
\"text\": \"$MONIT_BODY\" \
}" \
https://hooks.slack.com/services/<incoming>/<webhook url>/<your Slack API key>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment