2 min read | by Jordi Prats
To be able to use a secret on a Deployment (or generally speaking, any pod) we can choose to share it by using either volumes or environment variables. Let's take a look hwo it would look like using an volume mount.
Let's create first a secret with some data in it:
$ kubectl create secret generic democredentials \ --from-literal=username=jordi.prats \ --from-literal=password='not_so_secret'
Now we are going to create a pod for testing it but you can also use it for deployments, cronjobs, statefullsets and so on: Any other object that manages a pod can use it in the same way:
apiVersion: v1 kind: Pod metadata: name: secret2file spec: containers: - name: demo image: busybox command: ["sleep"] args: ["1h"] # mount volume at a given path; secret to volume declared below: volumeMounts: - name: democredentialsvolume mountPath: /etc/democredentials volumes: # secret as volume - name: democredentialsvolume secret: secretName: democredentials
We are declaring here a volume from the secret we have already created democredentials named democredentialsvolume that's going to be mounted on /etc/democredentials
We just need to apply this yaml file using kubectl apply
$ kubectl apply -f secret2filepod.yaml pod/secret2file created
We'll have to check that's already running:
$ kubectl get pod secret2file NAME READY STATUS RESTARTS AGE secret2file 1/1 Running 1 23s
Once it's running, we can use kubectl exec to run commands on the pod for checking the contents of /etc/democredentials. We will see the secret as a directory with each key within the secret as a file:
$ kubectl exec -i pod/secret2file -- ls -l /etc/democredentials total 0 lrwxrwxrwx 1 root root 15 Dec 29 09:49 password -> ..data/password lrwxrwxrwx 1 root root 15 Dec 29 09:49 username -> ..data/username
Inside each file we will be able to see the value for each key we have in the secret
$ kubectl exec -i pod/secret2file -- cat /etc/democredentials/username jordi.prats $ kubectl exec -i pod/secret2file -- cat /etc/democredentials/password not_so_secret
Posted on 05/01/2021