Skip to content

Instantly share code, notes, and snippets.

@kchristensen
Created December 17, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kchristensen/ac513cef572b33826652 to your computer and use it in GitHub Desktop.
Save kchristensen/ac513cef572b33826652 to your computer and use it in GitHub Desktop.
Watches docker to see if any of your containers have exited abnormally and notifies slack
#!/bin/bash
INSTANCE=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
SLACK_CHANNEL='#ops-notifications'
SLACK_URL='<%= node['base']['slack']['hook'] %>'
SLACK_USERNAME='DockerBot'
for CONTAINER in $(docker ps -a|grep -v CONTAINER|awk '{print $1}')
do
STATE=$(docker inspect -f '{{.State.Running}}' ${CONTAINER})
# We're only concerned with containers that aren't running
if [ "$STATE" != "true" ];
then
EXIT_CODE=$(docker inspect -f '{{.State.ExitCode}}' ${CONTAINER})
# Don't notify Slack on normal container shutdown
if [ ${EXIT_CODE} -gt 0 ];
then
CONTAINER_NAME=$(docker inspect -f '{{.Config.Image}}' ${CONTAINER}|awk -F/ '{print $2}'|awk -F: '{print $1}')
SLACK_TEXT="Container ${CONTAINER_NAME} running on ${INSTANCE} exited with code ${EXIT_CODE}"
curl -X POST --data "payload={\"channel\": \"${SLACK_CHANNEL}\", \"username\": \"${SLACK_USERNAME}\", \"text\": \"${SLACK_TEXT}\"}" ${SLACK_URL}
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment