Alternatively, we could use environment variables to retrieve secrets, which is more flexible for short credentials, such as a password. Applications are able to use environment variables to retrieve database passwords without tackling files and volumes:
// example to use environment variable to retrieve the secret
# cat 3-2-3_pod_ev_secret.yaml
apiVersion: v1
kind: Pod
metadata:
name: secret-access-ev
spec:
containers:
- name: centos
image: centos
command: ["/bin/sh", "-c", "while : ;do echo $MY_PASSWORD; sleep 10; done"]
env:
- name: MY_PASSWORD
valueFrom:
secretKeyRef:
name: mypassword
key: mypassword
// create the pod
# kubectl create -f 3-2-3_pod_ev_secret.yaml
pod "secret-access-ev" created
A secret should always be created before the pods that need it. Otherwise, the pods won't be launched successfully.
The declaration is under spec.containers[].env[]. We'll need the secret name and the key name. Both are mypassword in this case. The example should work the same as the one we looked at previously.