How to Create and Use Secrets in KubernetesHow to Create and Use Secrets in Kubernetes

Prerequisites

This tutorial is written using Windows 10, kubectl, and minikube. If you have a similar setup you are good to go.

Important Note for Windows Users

All files you create must have Unix (LF) line endings, not Windows ( CR LF ) endings. Read your editor documentation on how to change it to default to LF line endings. There should also be some EOL conversion menu option somewhere to convert to LF.

Creating a Secret: kubectl Create Secret

Most applications need a database. Most databases need a username and password. Let’s create a simple secret that includes a username and password. This is a two step process:

  • Create files containing our secrets,
  • Use kubectl create secret generic to create a Kubernetes secret object.
echo -n 'dbadmin' > ./username.txt
echo -n 'db3344@@pwd' > ./password.txt
kubectl create secret generic my-db-secret-from-files --from-file=./username.txt --from-file=./password.txtsecret "my-db-secret-from-files" created
kubectl get secretsNAME                  TYPE                                  DATA   AGE
default-token-gs2wt kubernetes.io/service-account-token 3 4d23h
my-db-secret-from-files Opaque 2 32s
kubectl describe secrets/my-db-secret-from-filesName:         my-db-secret-from-files
Namespace: default
Labels: <none>
Annotations: <none>
Type: OpaqueData
====
password.txt: 26 bytes
username.txt: 18 bytes

Using Secrets

Creating secrets was a two step process. Using secrets requires just one step: accessing the secret via volume mounts.

nano mySecretPod.yamlapiVersion: v1
kind: Pod
metadata:
name: my-secret-pod
spec:
containers:
- name: my-secret-pod
image: alpine
imagePullPolicy: IfNotPresent
volumeMounts:
- name: my-volume
mountPath: "/etc/secret"
readOnly: true
volumes:
- name: my-volume
secret:
secretName: my-db-secret-from-files
kubectl create -f mySecretPod.yaml 

pod/my-secret-pod created
kubectl describe -f mySecretPod.yaml 

Name: my-secret-pod
Namespace: default
Priority: 0
PriorityClassName: <none>
Node: minikube/10.0.2.15
Start Time: Mon, 31 Dec 2018 10:36:14 +0200
Labels: <none>
Annotations: <none>
Status: Running
IP: 172.17.0.5
Containers:
my-secret-pod:
Container ID: docker://28cbd33320d5a4d309615cc7d0a4c970bdc22b9f4edd84c7c8019dfa7d9153ff
Image: alpine
Image ID: docker-pullable://alpine@sha256:46e71df1e5191ab8b8034c5189e325258ec44ea739bba1e5645cff83c9048ff1
Port: <none>
Host Port: <none>
Command:
/bin/ash
-ec
while :; do echo '.'; sleep 15 ; done
State: Running
Started: Mon, 31 Dec 2018 10:36:15 +0200
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/etc/secret from my-volume (ro)
/var/run/secrets/kubernetes.io/serviceaccount from default-token-gs2wt (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
my-volume:
Type: Secret (a volume populated by a Secret)
SecretName: my-db-secret-from-files
Optional: false
default-token-gs2wt:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-gs2wt
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 10s default-scheduler Successfully assigned default/my-secret-pod to minikube
Normal Pulled 9s kubelet, minikube Container image "alpine" already present on machine
Normal Created 9s kubelet, minikube Created container
Normal Started 9s kubelet, minikube Started container
mySecretPod.yaml with irrelevant stuff removed:::

Name: my-secret-pod
Containers:
my-secret-pod:
Image: alpine
Mounts:
/etc/secret from my-volume (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
my-volume:
Type: Secret (a volume populated by a Secret)
SecretName: my-db-secret-from-files
Optional: false
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 10s default-scheduler Successfully assigned default/my-secret-pod to minikube
Normal Pulled 9s kubelet, minikube Container image "alpine" already present on machine
Normal Created 9s kubelet, minikube Created container
Normal Started 9s kubelet, minikube Started container
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Mounts:
/etc/secret from my-volume (ro)
Volumes:
my-volume:
Type: Secret (a volume populated by a Secret)
SecretName: my-db-secret-from-files
kubectl exec my-secret-pod -i -t -- /bin/ash/ # ls /etc/secret/
password.txt username.txt
/ # cat /etc/secret/password.txt
db3344@@pwd
/ # cat /etc/secret/username.txt
dbadmin
/ # exit
nano mySecretPod.yamlapiVersion: v1
kind: Pod
metadata:
name: my-secret-pod
spec:
containers:
- name: my-secret-pod
image: alpine
imagePullPolicy: IfNotPresent

tty: true
stdin: true

command: ["/bin/ash", "-ec", "while :; do echo '.'; sleep 15 ; done"]
volumeMounts:
- name: my-volume
mountPath: "/etc/secret"
readOnly: true

volumes:
- name: my-volume
secret:
secretName: my-db-secret-from-files
  • .stdin : true Keep stdin open on the container in the pod
  • tty stands for TeleTYpewriter
  • .tty : true Allocates a TTY / terminal console for each container in the pod
kubectl create secret generic my-db-secret-from-files --from-file=./username.txt --from-file=./password.txt
/ # ls /etc/secret/
password.txt username.txt

Define Key Names Different from Filenames

When you used

kubectl create secret generic my-db-secret-from-files --from-file=./username.txt --from-file=./password.txt
kubectl create secret generic my-db-secret-new-key --from-file=<strong>user</strong>=./username.txt --from-file=pass=./password.txt
kubectl create secret generic my-db-secret-new-key --from-file=user=./username.txt --from-file=pass=./password.txtsecret/my-db-secret-new-key created
kubectl delete -f mySecretPod.yaml --force --grace-period=0warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
pod "my-secret-pod" force deleted
nano mySecretPod.yamlapiVersion: v1
kind: Pod
metadata:
name: my-secret-pod
spec:
containers:
- name: my-secret-pod
image: alpine
imagePullPolicy: IfNotPresent

tty: true
stdin: true

command: ["/bin/ash", "-ec", "while :; do echo '.'; sleep 15 ; done"]
volumeMounts:
- name: my-volume
mountPath: "/etc/secret"
readOnly: true

volumes:
- name: my-volume
secret:
secretName: my-db-secret-new-key
kubectl create -f mySecretPod.yamlpod/my-secret-pod created
kubectl describe secret/my-db-secret-new-keyName:         my-db-secret-new-key
Namespace: default
Labels: <none>
Annotations: <none>
Type: OpaqueData
====
<strong>pass</strong>: 26 bytes
<strong>user</strong>: 18 bytes
kubectl exec my-secret-pod -i -t -- /bin/ash/ # ls /etc/secret
pass user
/ # exit
kubectl delete -f mySecretPod.yaml --force --grace-period=0warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.

Files Containing Secrets in a Folder

Run the following at your shell:

mkdir secret-folderecho -n 'dbadmin' > ./secret-folder/username.txt
echo -n 'db3344@@pwd' > ./secret-folder/password.txt
kubectl create secret generic my-db-secret-demo --from-file=./secret-foldersecret/my-db-secret-demo created
kubectl get secretNAME                   TYPE                                  DATA   AGE
default-token-gs2wt kubernetes.io/service-account-token 3 5d2h
my-db-secret Opaque 2 129m
my-db-secret-demo Opaque 2 23s
my-db-secret-new-key Opaque 2 26m
kubectl describe secrets/my-db-secret-demoName: my-db-secret-demo
Namespace: default
Labels: <none>
Annotations: <none>
Type: OpaqueData
====
password.txt: 26 bytes
username.txt: 18 bytes

Use key=val Pairs to Create a Secret

Another way to create a secret is to have key=value pairs in a file.

nano env-file-demokey1=abc
key2=123
usera=test
usera-password=demo
kubectl create secret generic my-db-secret-env-file --from-env-file=./env-file-demosecret/my-db-secret-env-file created
kubectl describe secrets/my-db-secret-env-fileName:         my-db-secret-env-file
Namespace: default
Labels: <none>
Annotations: <none>
Type: OpaqueData
====
usera-password: 4 bytes
key1: 3 bytes
key2: 3 bytes
usera: 4 bytes

Create a Secret from a Literal

Note: This is the most insecure way to create a secret.

kubectl create secret generic my-literal-secret --from-literal=litkey1=insecure1 --from-literal=litkey2=passthewordsecret/my-literal-secret createdkubectl describe secret/my-literal-secret 

Name: my-literal-secret
Namespace: default
Labels: <none>
Annotations: <none>
Type: OpaqueData
====
litkey1: 9 bytes
litkey2: 11 bytes

Exercises

Following a step by step tutorial is easy. At work you will not have step by step instructions: you will have existing Pods that need minor mods.

  • modify every example given here: remove one of the keys,
  • modify every example given here: add one new key,
  • mount the secrets at a different directory — do at least one such exercise,
  • modify some existing YAML files during your experiments,
  • create new copies of YAML files — give all objects new names in this new YAML files.

Clean Up

Get a list of your secrets :

kubectl get secretsNAME                           TYPE                                  DATA   AGE
secret/default-token-gs2wt kubernetes.io/service-account-token 3 6d4h
secret/my-db-secret Opaque 2 28h
secret/my-db-secret-demo Opaque 2 26h
secret/my-db-secret-env-file Opaque 4 25h
secret/my-db-secret-new-key Opaque 2 26h
secret/my-literal-secret Opaque 2 6h7m
kubectl delete secret/my-db-secret
kubectl delete secret/my-db-secret-demo
kubectl delete secret/my-db-secret-env-file
kubectl delete secret/my-db-secret-new-key
kubectl delete secret/my-literal-secret
kubectl delete -f mySecretPod.yaml --force --grace-period=0

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

4.97K Followers

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com