#!/bin/bash
# This script listens for docker events which have one of the statuses matched below in test(...)
# then filters the output by exit codes which are non-zero and then prints the container ID.
# That container ID is then inspected by docker and the output written the filesystem (which is sent to CloudWatch Logs)

OFILE='/var/log/ng-docker-inspect-exited.log'
[[ ! -f "$OFILE" ]] && touch $OFILE

docker events --filter type=container --format '{{ json . }}' \
	| jq --raw-output --unbuffered 'select(.status | test("^(die|kill|oom|stop)"))| .Actor.ID' \
		| while read line; do
			docker inspect $line | jq --compact-output --unbuffered .[] >> "$OFILE"
		done
