Home Using Secrets in Kubernetes via environment variables
Post
Cancel

Using Secrets in Kubernetes via environment variables

This Kubernetes YAML file will create a namespace, a secret and a pod. The pod will run and immediately complete (by design). The namespace is not strictly needed but it is a good habit to get into. It provides additional isolation and a easy way to delete everything.

YAML file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
kind: Namespace
apiVersion: v1
metadata:
  name: secrets-n
  labels:
    name: secrets-l
---
apiVersion: v1
kind: Secret
metadata:
  namespace: secrets-n
  name: mysecret
type: Opaque
stringData:
  USERNAME: username1
  PASSWORD: password1
---
apiVersion: v1
kind: Pod
metadata:
  namespace: secrets-n
  name: secret-test-pod
spec:
  containers:
    - name: test-container
      image: registry.k8s.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - secretRef:
          name: mysecret
  restartPolicy: Never

Create the deployment

1
2
3
4
$ kubectl apply -f secrets.yaml
namespace/secrets-n created
secret/mysecret created
pod/secret-test-pod created

See the output

I have deleted variables not germane to this test.

1
2
3
4
$ kubectl logs pod/secret-test-pod -n secrets-n
HOSTNAME=secret-test-pod
USERNAME=username1
PASSWORD=password1

Delete the namespace

This will delete everything within the namespace.

1
2
$ kubectl delete ns secrets-n
namespace "secrets-n" deleted
This post is licensed under CC BY 4.0 by the author.