Skip to content

Instantly share code, notes, and snippets.

@timgentry
Forked from matt448/slack_nagios.sh
Last active March 22, 2017 00:00
Show Gist options
  • Save timgentry/49a5a8f8710eb09a2da2449eb6551bd6 to your computer and use it in GitHub Desktop.
Save timgentry/49a5a8f8710eb09a2da2449eb6551bd6 to your computer and use it in GitHub Desktop.
Script to post Nagios notifications into a Slack channel
#!/bin/bash
# This script is used by Nagios to post alerts into a Slack channel
# using the Incoming WebHooks integration. Create the channel, botname
# and integration first and then add this notification script in your
# Nagios configuration.
#
# All variables that start with NAGIOS_ are provided by Nagios as
# environment variables when an notification is generated.
# A list of the env variables is available here:
# http://nagios.sourceforge.net/docs/3_0/macrolist.html
#
# More info on Slack
# Website: https://slack.com/
# Twitter: @slackhq, @slackapi
#
# My info
# Website: http://matthewcmcmillan.blogspot.com/
# Twitter: @matthewmcmillan
#Modify these variables for your environment
MY_NAGIOS_HOSTNAME="nagios.yourdomain.com"
SLACK_HOSTNAME="yourslack.slack.com"
SLACK_TOKEN="xyxyxyourslackkey"
SLACK_CHANNEL="#alerts"
SLACK_BOTNAME="nagios"
#Set the message COLOUR based on Nagios service state
if [ "$NAGIOS_SERVICESTATE" = "CRITICAL" ]
then
COLOUR="\"color\": \"danger\","
elif [ "$NAGIOS_SERVICESTATE" = "WARNING" ]
then
COLOUR="\"color\": \"warning\","
elif [ "$NAGIOS_SERVICESTATE" = "OK" ]
then
COLOUR="\"color\": \"good\","
# elif [ "$NAGIOS_SERVICESTATE" = "UNKNOWN" ]
# then
# COLOUR=""
else
COLOUR=""
fi
# Split NAGIOS_SERVICEOUTPUT into a TITLE and TEXT
TITLE=`echo $NAGIOS_SERVICEOUTPUT | cut -d '-' -f 1`
TEXT=`echo $NAGIOS_SERVICEOUTPUT | cut -d '-' -f 2`
if [ "$TITLE" = "$TEXT" ]
then
TITLE=`echo $NAGIOS_SERVICEOUTPUT | cut -d ':' -f 1`
TEXT=`echo $NAGIOS_SERVICEOUTPUT | cut -d ':' -f 2`
fi
PAYLOAD="payload={
\"channel\": \"${SLACK_CHANNEL}\",
\"username\": \"${SLACK_USERNAME}\",
\"attachments\": [
{
\"fallback\": \"${NAGIOS_SERVICEOUTPUT}\", ${COLOUR}
\"title\": \"${TITLE}\",
\"title_link\": \"https://${MY_NAGIOS_HOSTNAME}/cgi-bin/nagios3/status.cgi?host=${NAGIOS_HOSTNAME}\",
\"text\": \"${TEXT}\",
\"fields\": [
{\"title\": \"Host\", \"value\": \"${NAGIOS_HOSTNAME}\", \"short\": true},
{\"title\": \"Service\", \"value\": \"${NAGIOS_SERVICEDISPLAYNAME}\", \"short\": false}
]
}
]
}"
#Send message to Slack
curl -X POST --data ${PAYLOAD} https://${SLACK_HOSTNAME}/services/hooks/incoming-webhook?token=${SLACK_TOKEN}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment