Secrets as environment variables

Secrets are referenced in the pod definition under the containers and env sections. We will use the secrets that we previously defined in a pod, and learn how to use them in an application: 

  1. Save the following configuration in a file called pod-with-env-secrets.yaml:
apiVersion: v1
kind: Pod
metadata:
name: secret-using-env
spec:
containers:
- name: nginx
image: nginx
env:
- name: SECRET_URL
valueFrom:
secretKeyRef:
name: myapi-url-token
key: secreturl.txt
- name: SECRET_TOKEN
valueFrom:
secretKeyRef:
name: myapi-url-token
key: secrettoken.txt
restartPolicy: Never

Under env, we define the env name as SECRET_URL. Then kubernetes gets the value by using the valueFrom. It is referred to a key in the secret data using secretKeyRef with the myapi-url-token name. Finally, take the value present in the secreturl.txt key.

Similarly, we ask the SECRET_TOKEN value to be set by using the value present in the secrettoken.txt key.

  1. Let's now create the pod and see whether it really worked:
kubectl create -f pod-with-env-secrets.yaml
  1. Check whether the environment variables are set correctly:
kc exec -it secret-using-env bash
root@secret-using-env:/# echo $SECRET_URL
https://my-secret-url-location.topsecret.com
root@secret-using-env:/# echo $SECRET_TOKEN
/x~Lhx Az!,;.Vk%[#n+";9p%jGF6[

Any application can use the secret values by referencing the appropriate env variables. Please note that both the application and the pod definition have no hardcoded secrets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset