What are Kubernetes Secrets?

A secret in the programming world refers to a sensitive data such as a password, a token, or a key. Kubernetes provides a way to store it on the pod without having to include it in your application image. This mechanism is called a Secret in the Kubernetes world.

Secrets are similar to configmap, however, they are specifically intended to hold confidential data. Read my post on Kubernetes Configmap

Creating a Secret

apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
username: YWRtaW4=
password: MWYyZDFlMmU2N2Rm
Manifest File for creating a Kubernetes Secret

Explanation

The serialised JSON and YAML values of Secret data are encoded as base64 strings.

Line 2: Defines the kind of the Kubernetes Object, which is Secret in this case. Line 3-4 define the metadata for secrets, similar to any other Kubernetes objects.

Line 6: Defines the data that defines the secrets.

Secrets have a size limit of 1MiB

Using a Secret

Secrets can be mounted as data volumes or exposed as environment variables to be used by a container in a Pod.

Using a secret as a file from a Pod

apiVersion: v1
kind: Pod
metadata:
name: example-secret
spec:
containers:
name: example-container
image: nginx
volumeMounts:
# name must match the volume name below
name: secret-volume
mountPath: /etc/secret-volume
readOnly: true
# The secret data is exposed to Containers in the Pod through a Volume.
volumes:
name: secret-volume
secret:
secretName: test-secret
Pod spec mounting the secret as a volume

Explanation

Line 9-13: This declares the volume mount details along with the path at which it should be pointed

Line 15-18: This declares the name of the secret that should be mounted.

Using a secret as an environment variable

apiVersion: v1
kind: Pod
metadata:
name: example-secret
spec:
containers:
name: example-container
image: nginx
env:
name: SECRET
valueFrom:
secretKeyRef:
name: test-secret
key: test-secret-key
view raw secretenv.yaml hosted with ❤ by GitHub
Pod spec declaring the environment variable from secret

Explanation

Line 9: This indicates that the details of the environment follows.

Line 11-14: These provide the details of the secret which needs to be set in the environment variable.

Securing Secrets

  1. Encryption at rest should be configured for secrets.
  2. Always configure least-privilege access to secrets.
  3. Restrict access to secrets to the specific container in the pod that requires to use the secret.
  4. Secrets should be protected after reading, that is, the application should ensure that it is dealing with secrets in an appropriate manner.
  5. Lastly, if the secrets are being configured via manifest, it should be ensured that these are not shared or checked in to a version control.

Conclusion

Kubernetes Secrets are a great way to ensure that the delivery of secrets are decoupled from the code.