Secrets
Secrets
You can create secrets with a YAML file. The following is an example:
echo admin | base64
YWRtaW4K
echo Password01 | base64
UGFzc3dvcmQwMQo=
apiVersion: v1
kind: Secret
metadata:
name: secret-user-pass
type: Opaque
data:
username: YWRtaW4K
password: UGFzc3dvcmQwMQo=
kubectl apply -f secret-user-pass.yaml
secret/secret-user-pass created
Additional fields may also be stored in a YAML file.
Use an editor to create secret-config.yaml.
apiVersion: v1
kind: Secret
metadata:
name: secret-config
type: Opaque
stringData:
config.yaml: |-
apiUrl: https://kubernetes.api.com/api/v1
username: admin
password: Password01
application: applicazione01
Then create the secret with:
kubectl create -f secret-config.yaml
You may look at the fields by getting the secret in YAML, and then passing the config.yaml
field through the decoder.
kubectl get secret secret-config -o yaml
echo '[stored value here]' | base64 -d
Export Secrets to a pod through a mounted volume.
Secrets may be passed to pods through mounted volumes or through environment variables.
The following is an example as to how volumeMounts
specified in a pod’s YAML file may be used:
apiVersion: v1
kind: Pod
metadata:
name: secret-pod
namespace: default
spec:
containers:
- name: secret-pod
image: r.deso.tech/library/busybox
command:
- sleep
- "10000"
volumeMounts:
- name: secret-path
mountPath: "/etc/secret-path"
readOnly: true
restartPolicy: Never
volumes:
- name: secret-path
secret:
secretName: secret-config
items:
- key: config.yaml
path: config.yaml
mode: 400
Then create the pod.
kubectl create -f secret-pod.yaml
pod/secret-pod created
After creating the pod, verify it is ready.
kubectl get pods
NAME READY STATUS RESTARTS AGE secret-pod 1/1 Running 0 7s
Once the pod is ready, exec a shell in the pod container.
kubectl exec -it secret-pod -- sh
You should see a prompt like this:
/ #
Once you are inside the busybox container, lets have a look at our secrets.
cd /etc/secret-path
ls -l
cat config.yaml
apiUrl: https://kubernetes.api.com/api/v1 username: admin password: Password01
Pass Secrets to a pod through an environment variable.
Now lets do an example where we can get these secrets through an environment variable.
apiVersion: v1
kind: Pod
metadata:
name: secret-pod-env
spec:
containers:
- name: secret-pod-env
image: r.deso.tech/library/busybox
command:
- sleep
- "10000"
env:
- name: SECRET_CONFIG
valueFrom:
secretKeyRef:
name: secret-config
key: config.yaml
- name: VARIABLE_EXAMPLE
valueFrom:
secretKeyRef:
name: secret-user-pass
key: password
restartPolicy: Never
Now lets create the pod.
kubectl create -f secret-pod-env.yaml
pod/secret-pod-env created
Lets go have a look.
kubectl exec secret-pod-env -- env
SECRET_CONFIG=apiUrl: https://ks.api.com/api/v1 username: admin password: Password01 application: applicazione01 VARIABLE_EXAMPLE=Password01 KUBERNETES_SERVICE_PORT_HTTPS=443