A Secret can be also mounted as volume by using the Secret type of the volume. The following is an example of how to use it:
// example of using Secret volume
# cat 2-7-3_volumes.yaml
apiVersion: v1
kind: Pod
metadata:
name: secret-example-volume
spec:
containers:
- name: ubuntu
image: ubuntu
command: ["/bin/sh", "-c", "while : ;do cat /secret/token; sleep 10; done"]
volumeMounts:
- name: secret-volume
mountPath: /secret
readOnly: true
volumes:
- name: secret-volume
secret:
secretName: access-token
items:
- key: 2-7-1_access-token
path: token
// create the Pod
kubectl create -f 2-7-3_volumes.yaml
pod "secret-example-volume" created
The preceding example will mount secret-volume into the /secret mount point inside the Pod. /secret will contain a file with the name token, which contains our access token. If we check the Pod details, it'll show that we mounted a read-only Secret volume:
// check the Pod details
# kubectl describe pods secret-example-volume
Name: secret-example-volume
...
Containers:
ubuntu:
...
Mounts:
/secret from secret-volume (ro)
...
Volumes:
secret-volume:
Type: Secret (a volume populated by a Secret)
SecretName: access-token
Optional: false
...
If we check the stdout, it'll show the Pod can properly retrieve the expected value:
# kubectl logs -f secret-example-volume
9S!g0U61699r
The same as with the environment variable, the files in the mounted volume are created upon Pod creation time. It won't change dynamically when the Secret value is updated after the Pod creation time.