Kubernetes - Secret
Kubernetes secret object let you store and mange sensitive information, such as passwords, OAuth tokens and SSH Keys. It is better to store this kind of secret in Kubernetes secret than in a container image.
NOTE: Creation of Secret and its usage is very similar to ConfigMap.
create secrets from Literal
Commands to create secret dev-db-secret with key username and password
1 | kubectl create secret generic dev-db-secret --from-literal=username='admin' --from-literal=password='password' |
Use kubectl get secrets
command to check the secret. DATA field shows the number of entries in the secret.
1 | $ kubectl get secrets |
Use kubectl describe secrets
command to get more details on the secret. The secret is not printed to the screen.
1 | $ kubectl describe secret/dev-db-secret |
Create Secret from File
First create file to store username ‘admin’ and password ‘password’ for database access
1 | $ echo -n 'admin' > .username.txt |
Use kubectl create secret
command to create secret
1 | kubectl create secret generic dev-db-secret --from-file=./username.txt --from-file=./password.txt |
Create Secret using YAML File
You can create the secret from yaml file using kubectl apply -f ./secret.yaml
command
secret.yaml
1 | apiVersion: v1 |
Getting the Content of a Secret
To retrieve the password
1 | $ kubectl get secret dev-db-secret -o yaml |
To decode the data, use base64 --decode
command
1 | $ echo 'YWRtaW4=' | base64 --decode |
Using Secret as Environment Variable
busybox-secret.yml : secrets are added to the container as environment variable
1 | apiVersion: v1 |
use kubectl logs busybox
command to check the pod’s logs. output:
1 | DBUSERNAME=admin |
Add Secret data to a Volume
busybox-secret.yaml: secret is add to volume with path db/dbusername and db/dbpassword. The volume is mount to path /etc/secret.
1 | apiVersion: v1 |
use kubectl logs secret-volume-test
to get the container output. output is
1 | admin |