Mounting a Secret
- Docker & Kubernetes course
- Intermediate
- Lesson 52/82
- 4 min
Learn to mount a Secret as environment or volume.
Using Secrets
Secrets are given to a container in the same ways as a ConfigMap: as environment variables with secretKeyRef/secretRef, or as files in a volume. Mounting as files is safer: environment variables can show up in crash dumps and child processes.
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-gizli
key: DB_PASSWORD
volumeMounts:
- name: tls
mountPath: /etc/tls
readOnly: true
volumes:
- name: tls
secret:
secretName: web-tlsFile permissions
The permissions of the files in a Secret volume can be restricted with defaultMode (an octal value). That way only the file owner can read them:
volumes:
- name: tls
secret:
secretName: web-tls
defaultMode: 0400
$ kubectl exec web -- ls -l /etc/tls/
-r-------- 1 root root ... tls.crt
-r-------- 1 root root ... tls.keyPractice Provide the password
Write a container section (starting with containers:): container named api, image api:1.0; under env, the DB_PASSWORD variable from the DB_PASSWORD key of the db-gizli Secret with secretKeyRef.
Starter code
# buraya yazSample solution
containers:
- name: api
image: api:1.0
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-gizli
key: DB_PASSWORDExpected output
deployment.apps/api configured
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which field gives the Secret's name in a volume?
- name
- secretRef
- key
- secretName Correct answer
Explanation: A ConfigMap volume uses name, a Secret volume uses secretName.
2 Take a single key from a Secret into an environment variable.
valueFrom:
____:
name: db-gizli
key: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-gizli
key: DB_PASSWORD
Explanation: secretKeyRef is a single key, secretRef all keys.
3 Match.
| Term | Meaning |
|---|---|
secretKeyRef |
Single-key env var |
secretRef |
All keys (envFrom) |
secretName |
Volume source |
defaultMode |
File permission |