Kubernetes secrets to a dotenv (.env) file

April 24, 2019 - 1 minute read -
kubernetes dotenv base64 bash

For dumb reasons, I recently needed to be able to quickly setup a local environment with secrets loaded from a kubernetes instance. After manually copying/pasting/decoding a few times, I decided to write a quick script to do it for me.

The following script grabs a kubernetes secrets file (${SECRET}) from kube, decodes each key/value pair and then appends them to a .env file.

Prerequisites: jq, kubectl

# base64 decode secrets file ${SECRET} and add each key=value pair to .env file
for s in $(kubectl get secret ${SECRET} -o json | jq -r ".data" | jq -r "to_entries|map(\"\(.key)=\(.value | @base64d)\")|.[]" ); do
    echo $s >> .env
done

The above script invokes jq twice, which was a quick and dirty workaround to get it working under alpineā€™s ash, in addition to bash.