This is a very short article – but it shows a handy way of getting and setting Kubernetes secret values as environment variables. You’ll need to be running this in a modern bash shell. The example I’ll use is related to the Workload identity with Kubernetes cronjobs to synch Mongo to Bigquery post, and will help you run it locally rather than in Kubernetes. Of course the same model can be used for any similar problems

Objective

Let’s say you have a kubernetes secret that contains everything you need to run your workload in a cluster. You want to test it locally and set some of the values in your local shell process without actually exposing them.

One way is to use doppler to manage secrets (see Sharing secrets between Doppler, GCP and Kubernetes), but if you’re not doing that a few lines of bash will take care of it for you.

Getting started

Make sure you are running in a bash shell. We’ll be using some syntax that is specific to bash.

Create this script

  • The first argument is the kubernetes namespace that holds the secret
  • The second is the secret’s name
  • The NAMES array contains the list of variables you want to set
  • You can use the ‘declare‘ statement to set a variable via an indirect name to a value (without the need to resort to ‘eval’)
#!/bin/bash

NS=$1
SECRETNAME=$2
NAMES=(
"DB_NAME" "DB_USER" "DB_PASSWORD" "DB_HOST"
)

for name in "${NAMES[@]}"
do

VALUE=$(kubectl get secret ${SECRETNAME} -n ${NS} -o jsonpath="{.data.${name}}" | base64 --decode)
declare -n ref="$name"
ref=$VALUE
export ref
done
get-secrets.bash get values from kube secrets

Executing in an existing script

Add this to an existing script to make the variables in NAMES visible to your script or child processes. So for example, “${DB_NAME}” will contain the value extracted from the Kubernetes secret

Getting the values into the current interactive shell

Values set in a script are not available to the parent (child process variables are not visible in the interactive shell). However, this syntax sets it in the current process rather than the child process.

. ./get-secrets.bash

Now echo ${DB_HOST}, for example, will show you the value for DB_HOST. You can simply run any scripts in you interactive shell that depend on environment values from the kubernets secret

Related