What are Secrets in Kubernetes?

Secrets in Kubernetes

A Secret in Kubernetes is an API object designed to store and manage sensitive information such as passwords, API keys, TLS certificates, and database credentials. Unlike ConfigMaps, which store non-sensitive configuration data, Secrets provide a more secure way to handle confidential information within a cluster.

By default, Kubernetes Secrets are stored in Base64-encoded format inside etcd (the cluster’s key-value store). While this isn’t encryption, it prevents sensitive values from being exposed as plain text in configuration files. However, additional security measures are required to properly protect Secrets.

Why Use a Secret Instead of a ConfigMap?

Using Secrets instead of ConfigMaps offers several benefits:

How Does it Work?

A Secret in Kubernetes can store:

Can be consumed by pods through:

Example: Creating a Secret

A Secret storing a database password:

apiVersion: v1
kind: Secret
metadata:
  name: db-secret
type: Opaque
data:
  DB_PASSWORD: c2VjdXJlLXJvbmRvbS1wYXNzd29yZA==  # Base64-encoded value

To manually encode a password:

echo -n "secure-random-password" | base64

Once created (kubectl apply -f secret.yaml), this Secret can be used by pods.

Using a Secret in a Pod (Environment Variables)

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: my-app
    image: my-app-image
    env:
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-secret
          key: DB_PASSWORD

Using a Secret as a Volume

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: my-app
    image: my-app-image
    volumeMounts:
    - name: secret-volume
      mountPath: "/etc/secrets"
  volumes:
  - name: secret-volume
    secret:
      secretName: db-secret

The Secret will be accessible as a file at /etc/secrets/DB_PASSWORD.

Common Challenges

1. Base64 Encoding Is Not Encryption

2. Default Storage Is Insecure

3. Access Control Issues

Best Practices

Popular Tools for Managing Kubernetes Secrets

Further Reading