Skip to content

Instantly share code, notes, and snippets.

@twoixter
Created September 24, 2024 19:22
Show Gist options
  • Save twoixter/bf991da57a838e648811141cb8284f25 to your computer and use it in GitHub Desktop.
Save twoixter/bf991da57a838e648811141cb8284f25 to your computer and use it in GitHub Desktop.
Consul watch script to update certificates based on a key prefix
#!/bin/bash
# This bash script handles input from consul 'watch' for keys holding
# certificates in PEM format. For this to correctly handle certificates
# the Consul key **MUST** have the following schema:
#
# certificates/<Domain Name>/<Filename>
#
# For example, this is how we handle keys for Consul server certificates:
#
# certificates/mdi-consul.mktgoo.net/privkey.pem
# certificates/mdi-consul.mktgoo.net/fullchain.pem
#
LOGFILE=/var/log/consul-certificates.log
DESTINATION=/etc/nginx/certs
PREFIX=certificates/
_log() {
echo `date -Isec` "$@" | tee -a ${LOGFILE}
}
# Handle consul watch output with 'jq'. We can handle both an array of
# objects or individual objects.
_log "Receiving changes from Consul Watch..."
for row in $(jq -rc 'if type=="array" then .[] else . end | {Key, Value} | @base64'); do
_jq() {
echo ${row} | base64 --decode | jq -r ${1}
}
ORIGINAL_NAME=$(_jq '.Key')
DIRNAME=$(dirname ${ORIGINAL_NAME#$PREFIX})
FILENAME=$(basename ${ORIGINAL_NAME})
# _log "DEBUG: Original name = '${ORIGINAL_NAME}'"
# _log "DEBUG: Extracted dirname = '${DIRNAME}'"
# _log "DEBUG: Extracted filename = '${FILENAME}'"
# Consul also ouputs the Key 'certificates/' and 'certificates/domain/'
# as changed Keys so we need to filter out these. Both situations will
# have '.' as $DIRNAME since we strip out the 'certificates/' part.
case $DIRNAME in
""|".")
_log "Skipping Key '${ORIGINAL_NAME}'"
continue ;;
esac
FULLNAME=${DESTINATION}/${DIRNAME}/${FILENAME}
_log "Saving file '${FULLNAME}'..."
CONTENTS=$(_jq '.Value')
mkdir -p $(dirname ${FULLNAME})
echo ${CONTENTS} | base64 --decode > ${FULLNAME}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment