Skip to content

Instantly share code, notes, and snippets.

@byrnedo
Created May 15, 2018 08:56
Show Gist options
  • Save byrnedo/18bbf33cf967c516dc80ab6588da977e to your computer and use it in GitHub Desktop.
Save byrnedo/18bbf33cf967c516dc80ab6588da977e to your computer and use it in GitHub Desktop.
Check urls for 200s or send slack message
#!/bin/bash
WORK_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
set -ueo pipefail
checkTimeout=6
SEND_ERROR_MAIL=1
cd "$WORK_DIR"
function send_to_slack {
local status=$1
local service=$2
local color=good
local image=""
local pretext=""
local slack_url="<CHANGEME>"
case $status in
200)
color="good"
pretext="Website responding normally."
image="https://res.cloudinary.com/byrnedo/image/upload/v1457347239/godmode_ofwzk7.jpg"
;;
*)
color="danger"
pretext="Website returned unexpected status $status"
image="https://res.cloudinary.com/byrnedo/image/upload/v1457345752/doom_fvhzga.png"
;;
esac
attachment="{\"fallback\":\"$service: http check status is $status\",\"title\":\"$service: http check status is $status\",\"pretext\":\"$pretext\",\"color\":\"$color\",\"thumb_url\":\"$image\",\"fields\":[{\"title\":\"Service\",\"value\":\"$service\",\"short\":true},{\"title\":\"Url\",\"value\":\"https://${service}\",\"short\":true},{\"title\":\"Status\",\"value\":\"$status\",\"short\":true}]}"
curl --silent -X POST -H 'Content-type: application/json' --data-binary @- $slack_url << EOFF
{
"channel": "service-alerts",
"attachments": [
$attachment
]
}
EOFF
}
for service in acme.example.com acme2.example.com
do
set +e
# do curl
code=$(curl -s -o /dev/null -w "%{http_code}" -L "https://${service}")
set -e
echo "Result ${code}"
result="$code"
if [[ ${result} -ne 200 ]]
then
echo "error code ${result} checking ${service}"
sendMail=0
if [[ -f ./LAST_ALERT_NOTICE_${service} ]]
then
if [[ $(( (`date +%s` - `stat -L --format %Y ./LAST_ALERT_NOTICE_${service}`) > (10*60) )) -eq 1 ]]
then
rm ./LAST_ALERT_NOTICE_${service}
sendMail=${SEND_ERROR_MAIL}
else
echo not sending notice as less than 10 minutes since last
fi
else
touch ./LAST_ALERT_NOTICE_${service}
sendMail=${SEND_ERROR_MAIL}
fi
if [[ ${sendMail} -eq ${SEND_ERROR_MAIL} ]]
then
send_to_slack ${result} ${service}
fi
else
echo "healthy response from ${service}"
if [[ -f ./LAST_ALERT_NOTICE_${service} ]]
then
echo "Sending service ok notice"
send_to_slack ${result} ${service}
rm ./LAST_ALERT_NOTICE_${service}
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment