Skip to content

Instantly share code, notes, and snippets.

@johnorourke
Last active April 21, 2020 14:55
Show Gist options
  • Save johnorourke/fedca065f63594cb99ad56a90aadfe2b to your computer and use it in GitHub Desktop.
Save johnorourke/fedca065f63594cb99ad56a90aadfe2b to your computer and use it in GitHub Desktop.
#!/bin/bash
set -euo pipefail
err() {
echo $1 >>/dev/stderr
rm -f $TMP_SNAPSHOT_FILE
exit 3
}
trap "err 'Error while running monitoring commands'" ERR
CONFIG_SNAPSHOT_FILE=/tmp/check_digitalocean_config_snapshot.json
TMP_SNAPSHOT_FILE=`tempfile`
API="https://api.digitalocean.com/v2"
TOKEN=""
ID=""
ACKNOWLEDGE=0
# thanks to https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash/29754866
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-t|--token)
TOKEN="$2"
shift # past argument
shift # past value
;;
-u|--url)
API="$2"
shift # past argument
shift # past value
;;
-i|--id)
ID="$2"
shift # past argument
shift # past value
;;
--acknowledge)
ACKNOWLEDGE=1
shift
;;
*)
err "Unknown command option - run without parameters for usage"
;;
esac
done
if [ -z "$TOKEN" -o -z "$ID" ]; then
echo "Usage: $0 -t|--token <DO token> -i|--id <unique ID for this DO token> [ --acknowledge ] [ -u|--url <DO URL up including /v2> ]" >>/dev/stderr
exit 3
fi
CONFIG_SNAPSHOT_FILE="$CONFIG_SNAPSHOT_FILE.$ID"
JQ=`which jq`
if [ -z "$JQ" ]; then
echo "Could not find 'jq' for JSON parsing"
exit 2
fi
CURL=`which curl`
if [ -z "$CURL" ]; then
echo "Could not find 'curl'"
exit 2
fi
DIFF=`which diff`
if [ -z "$DIFF" ]; then
echo "Could not find 'diff'"
exit 2
fi
diff() {
$DIFF --suppress-common-lines --ignore-space-change --ignore-blank-lines $1 $2
}
curl() {
$CURL --connect-timeout 20 --silent --show-error --header 'Content-Type: application/json' --header "Authorization: Bearer $TOKEN" $API$1 | jq "$2"
}
(
for i in /domains /databases /certificates /droplets /load_balancers /account/keys /images /firewalls /floating_ips; do
curl $i '. | del(.links?) | del(.meta?)'
done
) | jq --slurp add >$TMP_SNAPSHOT_FILE
if [ ! -w $CONFIG_SNAPSHOT_FILE ]; then
cp $TMP_SNAPSHOT_FILE $CONFIG_SNAPSHOT_FILE || err "Failed to copy new to old snapshot!"
echo "Initialising with new state"
exit 3
fi
set +e
trap - ERR
diff $CONFIG_SNAPSHOT_FILE $TMP_SNAPSHOT_FILE
DIFFRESULT=$?
if [ $DIFFRESULT -eq 2 ]; then
err 'Failed to run diff'
fi
if [ $DIFFRESULT -eq 1 ]; then
if [ $OVERWRITE -eq 1 ]; then
cp $TMP_SNAPSHOT_FILE $CONFIG_SNAPSHOT_FILE
echo "Infrastructure changes acknowledged!"
rm -f $TMP_SNAPSHOT_FILE
exit 1
fi
echo "Infrastructure changes detected! Run with --acknowledge to acknowledge and update the stored config!"
rm -f $TMP_SNAPSHOT_FILE
# exit code 2 = critical
exit 2
fi
rm -f $TMP_SNAPSHOT_FILE
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment