Featured image of post Kubernetes Secrets: A Complete Guide with Code Examples

Kubernetes Secrets: A Complete Guide with Code Examples

Kubernetes Secrets: A Complete Guide with Code Examples

Kubernetes Secrets: A Complete Guide with Code Examples

Managing sensitive data in Kubernetes is critical. Whether it’s API keys, database credentials, or TLS certificates, Kubernetes Secrets provide a secure way to store and manage sensitive information.

By the end of this guide, you’ll understand:
What Kubernetes Secrets are and why they matter
How to create, manage, and secure Kubernetes Secrets
Different types of Secrets and when to use them
Best practices for protecting sensitive data in Kubernetes

Let’s get started! 🚀


1. What Are Kubernetes Secrets?

Kubernetes Secrets are objects designed to store sensitive information, such as:

  • 🔑 API Keys
  • 🗝 Passwords
  • 🔒 TLS Certificates
  • 🏦 Database Credentials

Secrets prevent hardcoding sensitive data in ConfigMaps, YAML files, or environment variables.

Why Use Secrets Instead of ConfigMaps?

FeatureConfigMapsSecrets
Data TypePlaintextBase64-encoded (not encrypted)
Used ForApp configsSensitive data
Access ControlStandardMore restrictive
Mounted AsVolumes or Env VarsVolumes or Env Vars
Security LevelLowMedium (requires extra security measures)

2. Creating and Managing Kubernetes Secrets

2.1 Creating a Secret from a File

First, create a plaintext file:

1
echo -n "supersecurepassword" > password.txt

Now, create a Kubernetes Secret:

1
kubectl create secret generic my-secret --from-file=password.txt

Verify:

1
2
kubectl get secrets
kubectl describe secret my-secret

2.2 Creating a Secret from Key-Value Pairs

1
kubectl create secret generic my-db-secret   --from-literal=username=admin   --from-literal=password=supersecurepassword

Retrieve it:

1
kubectl get secret my-db-secret -o yaml

Note: Data is base64-encoded, NOT encrypted!

Decode the password:

1
echo "c3VwZXJzZWN1cmVwYXNzd29yZA==" | base64 --decode

2.3 Creating a Secret Using a YAML File

Create secret.yaml:

1
2
3
4
5
6
7
8
apiVersion: v1
kind: Secret
metadata:
  name: my-secret
type: Opaque
data:
  username: YWRtaW4=   # Base64 encoded "admin"
  password: c3VwZXJzZWN1cmVwYXNzd29yZA==  # Base64 encoded "supersecurepassword"

Apply it:

1
kubectl apply -f secret.yaml

3. Using Kubernetes Secrets in Pods

3.1 Using Secrets as Environment Variables

Modify pod.yaml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
apiVersion: v1
kind: Pod
metadata:
  name: secret-pod
spec:
  containers:
  - name: my-container
    image: nginx
    env:
    - name: DB_USERNAME
      valueFrom:
        secretKeyRef:
          name: my-db-secret
          key: username
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: my-db-secret
          key: password

Apply:

1
kubectl apply -f pod.yaml

3.2 Mounting Secrets as Volumes

Modify pod-volume.yaml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
apiVersion: v1
kind: Pod
metadata:
  name: secret-volume-pod
spec:
  containers:
  - name: my-container
    image: nginx
    volumeMounts:
    - name: secret-volume
      mountPath: "/etc/secret-data"
      readOnly: true
  volumes:
  - name: secret-volume
    secret:
      secretName: my-db-secret

Apply:

1
kubectl apply -f pod-volume.yaml

Access secrets inside the pod:

1
kubectl exec -it secret-volume-pod -- cat /etc/secret-data/password

4. Securing Kubernetes Secrets

4.1 Enabling Role-Based Access Control (RBAC)

Create an RBAC policy to restrict Secret access:

1
2
3
4
5
6
7
8
9
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: secret-reader
rules:
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["get", "list"]

Create a RoleBinding:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: secret-reader-binding
  namespace: default
subjects:
- kind: User
  name: developer
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: secret-reader
  apiGroup: rbac.authorization.k8s.io

Apply:

1
kubectl apply -f rbac-secret.yaml

4.2 Encrypting Secrets at Rest

By default, Secrets are stored unencrypted in etcd. Enable encryption at rest:

Modify encryption-config.yaml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
      - secrets
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: c3VwZXJzZWN1cmVwYXNzd29yZA==
      - identity: {}

Apply:

1
kubectl apply -f encryption-config.yaml

4.3 Using External Secret Management Systems

Use HashiCorp Vault or AWS Secrets Manager for added security.

Vault Integration Example

1
vault kv put secret/myapp username=admin password=supersecurepassword

Retrieve secret:

1
vault kv get secret/myapp

5. Best Practices for Kubernetes Secrets

Use RBAC to restrict access to Secrets
Enable encryption at rest for Secrets
Avoid storing Secrets in ConfigMaps or environment variables
Use a Secret Management System (Vault, AWS Secrets Manager)
Monitor access to Secrets using audit logs
Regularly rotate Secrets and enforce expiration policies


Final Thoughts

Kubernetes Secrets help manage sensitive data securely, but they must be properly secured.

Key Takeaways

Secrets prevent hardcoding sensitive data in Pods
Use RBAC and encryption to protect Secrets
External secret managers enhance security
Monitor and audit Secret access in production

With proper management, Kubernetes Secrets enhance security while keeping configurations manageable. 🚀