Skip to content

Instantly share code, notes, and snippets.

@taxilian
Last active January 9, 2024 19:41
Show Gist options
  • Save taxilian/baf331ebacd575b46f27a0d21d7df97d to your computer and use it in GitHub Desktop.
Save taxilian/baf331ebacd575b46f27a0d21d7df97d to your computer and use it in GitHub Desktop.
Helper to extract TLS certificates from a kubernetes TLS secret and write them to files, handy for client authentication certs
#!/bin/bash
TMPFILE=$(mktemp)
function cleanup {
echo "Deleting $TMPFILE..."
rm -rv "$TMPFILE"
}
trap cleanup EXIT
function usage {
echo "usage: Pipe the json output of the kubectl get secret command into this script. The argument is the base for the output files"
echo ""
echo "e.g. 'kubectl -n mynamespace get secret my-certificate-tls -o json | ./extractCert.sh taxilian-cert'"
echo "Output filenames will be e.g. taxilian-cert-ca.crt, taxilian-cert.crt, taxilian-cert.key, taxilian-cert.pem"
exit 1
}
# if the jq command isn't installed, then print usage and die
if ! [ -x "$(command -v jq)" ]; then
echo 'Error: jq is not installed.' >&2
usage
fi
if [ -p /dev/stdin ]; then
cat /dev/stdin > "$TMPFILE"
echo "Wrote to $TMPFILE"
cat "$TMPFILE"
else
usage
fi
# if an argument isn't provided then print usage and die
if [ -z "$1" ]; then
usage
fi
FILEBASE=$1
# use jq to extract the base64 encoded cert and key from the json
jq -r '.data["tls.crt"]' < "$TMPFILE" | base64 -d > "${FILEBASE}.crt"
echo "Wrote to ${FILEBASE}.crt"
jq -r '.data["tls.key"]' < "$TMPFILE" | base64 -d > "${FILEBASE}.key"
echo "Wrote to ${FILEBASE}.key"
jq -r '.data["ca.crt"]' < "$TMPFILE" | base64 -d > "${FILEBASE}-ca.crt"
echo "Wrote to ${FILEBASE}-ca.crt"
if (jq -e '.data | has("tls-combined.pem")' < "$TMPFILE") > /dev/null; then
echo "Using tls-combined.pem"
jq -r '.data["tls-combined.pem"]' < "$TMPFILE" | base64 -d > "${FILEBASE}.pem"
echo "Wrote to ${FILEBASE}.pem"
else
echo "tls-combined.pem not found, creating it..."
cat "${FILEBASE}.key" > "${FILEBASE}.pem"
echo "" >> "${FILEBASE}.pem"
cat "${FILEBASE}.crt" >> "${FILEBASE}.pem"
echo "Wrote to ${FILEBASE}.pem"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment