Skip to content

Instantly share code, notes, and snippets.

@allanger
Last active May 12, 2022 16:13
Show Gist options
  • Save allanger/473ede4bf1f1a89d938a264a0cc6853c to your computer and use it in GitHub Desktop.
Save allanger/473ede4bf1f1a89d938a264a0cc6853c to your computer and use it in GitHub Desktop.
ZSH function to decode k8s secrets
# ------------------------------------
# -- Kubernetes reveal secrets
# ------------------------------------
# -- Just an alias
# ------------------------------------
alias krs="k8s_reveal_secret"
# ------------------------------------
# -- Internal function for generating
# -- the "$KEY: $VALUE" string
# ------------------------------------
function append_to_secret() {
SECRET=$1
KEY=$2
VALUE=$(kubectl get secret $SECRET -o yaml| yq ".data.\"$KEY\"" | base64 -d)
if (( $(grep -c . <<<"$VALUE") > 1 )); then
SECRET="$KEY: |-\n$(echo $VALUE| sed -e 's/^/ /')"
else
SECRET="$KEY: $VALUE"
fi
echo $SECRET
}
# ------------------------------------
# -- The main function that is doing
# -- everything
# ------------------------------------
function k8s_reveal_secret() {
if [[ "$1" != "" ]]; then
SECRET=""
if [[ $2 != "" ]]; then
SECRET=$(append_to_secret $1 $2)
else
for KEY in $(kubectl get secret $1 -o yaml | yq '.data | keys' | sed -e "s/- //"); do
SECRET="$SECRET\n$(append_to_secret $1 $KEY)";
done
fi
echo $SECRET | yq
else
echo "You should've at least passed a secret name"
fi
}
# ------------------------------------
# -- Completions
# ------------------------------------
function _k8s_reveal_secret(){
local state
_arguments -C \
"1: :->cmds" \
"2::arg:->args"
case "$state" in
cmds)
_values compadd $(kubectl get secrets --no-headers -o custom-columns=":metadata.name")
;;
args)
_values compadd $(for KEY in $(kubectl get secret $line[1] -o yaml | yq '.data | keys' | sed -e "s/- //"); do echo $KEY; done)
;;
esac
}
compdef _k8s_reveal_secret k8s_reveal_secret
# ------------------------------------
# -- The end...
# ------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment