Skip to content

Instantly share code, notes, and snippets.

@twoixter
Last active August 13, 2024 16:56
Show Gist options
  • Save twoixter/e97d829b6f46edce757f09fb8fb2d283 to your computer and use it in GitHub Desktop.
Save twoixter/e97d829b6f46edce757f09fb8fb2d283 to your computer and use it in GitHub Desktop.
Consul watch script to use templates with envsubst
#!/bin/bash
# This bash script handles input from Consul Watch (JSON) in order to be able
# to use "envsubst" to fill arbitrary file templates. It handles both single
# as well as multi-object inputs. E.G: JSON strings like "{ object }" or
# "[ {}, {}, array of objects ]".
#
# Usage:
# - Object JSON from Consul comes from standard input.
# - You must provide a file template from which ENV substitution will be made.
# - Consul KEYS are parsed so multi-level keys are parsed and the last
# slug is used in UPPERCASE for ENV substitution.
#
# Example:
# $ cat consul.json | ./test.consul.sh /usr/local/config.template
#
# consul.json: {"Key":"foo/bar/baz", "Value":"TU9BUg==", ...}
# config.template: baz_value = $BAZ
#
# Create temporary file for setting up environment
TEMP_FILE="$(mktemp -q /tmp/consul.env.XXXXXXXXX)" || exit 1
# Set trap to clean up file
trap 'rm -f -- "$TEMP_FILE"' EXIT
jq -rc 'if type=="array" then .[] else . end | [(.Key | split("/") | last | ascii_upcase), (.Value | @base64d)] | "export " + join("=")' > $TEMP_FILE
source "$TEMP_FILE"
envsubst < $1
# Clean up temporary file
rm -f -- "$TEMP_FILE"
# trap - EXIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment