Skip to content

Instantly share code, notes, and snippets.

@colebrooke
Last active August 18, 2017 08:38
Show Gist options
  • Save colebrooke/5f1f52a0c0f782cd0207610aea232032 to your computer and use it in GitHub Desktop.
Save colebrooke/5f1f52a0c0f782cd0207610aea232032 to your computer and use it in GitHub Desktop.
Script to allow nagios to generate a slack notification
#!/bin/bash
# Slack notification script, for use by Nagios or other similar monitoring systems.
#
# Author: Justin Miller
# Github: github.com/colebrooke
#
# Usage:
#
# ./nagios_notify_slack.sh <SLACKCHANNEL>
# You need to set up a custom command, contact, contact group and maybe service definition in nagios to trigger this script
# Nagios sets the environment variables, e.g. ${NAGIOS_SERVICEDISPLAYNAME} which are used by the script.
# Set prefered emojis
IDENT_EMOJI=":ng:"
WARN_EMOJI=":warning:"
CRITICAL_EMOJU=":bangbang:"
UNKNOWN_EMOJI=":question:"
OK_EMOJI=":white_check_mark:"
BOT_NAME="nagios"
NAGIOS_URL="mynagios.example.com"
# Slack channel is 1st script argument
CHANNEL="#$1"
# Generate your webhook in Slack: Browse Apps > Custom Integrations > Incoming WebHooks
SLACK_WEBHOOK="https://hooks.slack.com/services/T0xxxxxx/B6Nxxxxxx/xxxxxxxEXAMPLExxxxxxx"
case $NAGIOS_SERVICESTATE in
"CRITICAL" )
MESSAGE="*CRITICAL* service alert <!everyone>"
EMOJI=$CRTIICAL_EMOJI
;;
"WARNING" )
MESSAGE="*WARNING* service alert"
EMOJI=$WARN_EMOJI
;;
"OK" )
MESSAGE="*OK* service recovered"
EMOJI=$OK_EMOJI
;;
* )
MESSAGE="*UNKNOWN*service alert"
EMOJI=$UNKNOWN_EMOJI
;;
esac
# Remove double quotes from nagios output, as may break payload
OUTPUT=$(echo ${NAGIOS_SERVICEOUTPUT} | tr -d '"')
MESSAGE="${MESSAGE} on *${NAGIOS_HOSTNAME}* \n*SERVICE:* ${NAGIOS_SERVICEDISPLAYNAME} \n*OUTPUT:* ${OUTPUT} \n<https://${NAGIOS_URL}/cgi-bin/nagios3/status.cgi?host=${NAGIOS_HOSTNAME}|See the details on the nagios server>"
PAYLOAD="payload={\"channel\": \"${CHANNEL}\", \"username\": \"${BOT_NAME}\", \"text\": \"${EMOJI} ${MESSAGE}\", \"icon_emoji\": \"${IDENT_EMOJI}\", \"mrkdwn\": true}"
# Send notification
curl -X POST --data-urlencode """${PAYLOAD}""" ${SLACK_WEBHOOK}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment