kubernetes: Secrets

In the last article we studied about one type of object known as ConfigMaps that is a way which allows us to store information in the form of key value pairs and refer them in pod definition file for use.Let's assume that we want to deploy a MySQL database on a pod. To successfully deploy MySQL pod, we need to pass database username and password as arguments.We will all agree that passwords are always critical and should not be exposed publicly.
Next question that pops up in the mind is that "is there any way to hide such values in kubernetes?". The answer is yes and the object type that facilitate this is known as a secret.
There are two basic steps involved in using secrets
Create the secret
Inject it in to pod
Create your own secret
We are now going to see how to create a secret. One point here is username and password given here are human readable so first we will find a way to encrypt it as well.On a Unix operating system this can be achieved by using a base64 hash.
Suppose username is admin and password is Passw0rd . Execute the below command on the kubernetes cluster.
[root@node1 secret]# echo -n 'admin' | base64
YWRtaW4=
[root@node1 secret]# echo -n 'Passw0rd' | base64
UGFzc3cwcmQ=
[root@node1 secret]# cat secret-demo.yaml
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
username: YWRtaW4=
password: UGFzc3cwcmQ=
To create a secret execute
kubectl create -f secret-demo.yaml
To view the contents of secret or in other words to decode it execute
kubectl get secret mysecret -o yaml
Use the secret that we have created in a pod
apiVersion: v1
kind: Pod
metadata:
name: secret-test-pod
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
command: [ "/bin/sh", "-c", "env" ]
envFrom:
- secretRef:
name: mysecret
restartPolicy: Never
[root@node1 secret]# kubectl create -f pod-with-secret.yaml
pod/secret-test-pod created
[root@node1 secret]# kubectl get pods | grep -i secret
secret-test-pod 0/1 Completed 0 29s
[root@node1 secret]#
This is how we can secure sensitive data using secrets. Hope this was helpful.