Skip to main content
Kubernetes Introduction
CHAPTER 08 Intermediate

ConfigMaps and Secrets

Updated: May 15, 2026
20 min read

# CHAPTER 8

ConfigMaps and Secrets

1. Introduction

In modern software engineering, adhering to the 12-Factor App methodology is critical. One of its core tenets states: "Store config in the environment." You should never hardcode configuration data (like database URLs) or sensitive data (like API keys) directly into your application code or your Docker images. In Kubernetes, this decoupling is achieved using two specialized objects: ConfigMaps for non-sensitive data, and Secrets for highly sensitive data.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the purpose of ConfigMaps and Secrets.
  • Author ConfigMap and Secret YAML manifests.
  • Inject ConfigMaps as Environment Variables into a Pod.
  • Mount Secrets as physical files inside a Pod's filesystem.
  • Understand the base64 encoding requirement for Secrets.

3. Beginner-Friendly Explanation

Imagine a soldier (The Pod) receiving a mission briefing.
  • Hardcoding (Bad): The soldier tattoos the mission target and the nuclear launch codes onto their arm. If the mission changes, they need a new arm (a new Docker image rebuild). If captured, the enemy instantly reads the codes.
  • ConfigMap (Good - Non-Sensitive): The commander hands the soldier a piece of paper (ConfigMap) containing the weather report and the radio frequencies. If the weather changes, the commander just hands them a new piece of paper. No tattoos required.
  • Secret (Good - Sensitive): The commander hands the soldier a locked, encrypted briefcase (Secret) containing the nuclear launch codes. The briefcase is only opened when absolutely necessary.

4. ConfigMaps (Non-Sensitive Data)

A ConfigMap is a dictionary of key-value pairs. It is used to store things like application themes, log levels, or external service URLs.

Example configmap.yaml:

yaml
1234567
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_COLOR: "blue"
  LOG_LEVEL: "debug"

5. Secrets (Sensitive Data)

Secrets operate identically to ConfigMaps, but they are designed to hold passwords, SSH keys, and TLS certificates. *Important:* In a standard Kubernetes Secret YAML, the values MUST be Base64 Encoded.

Example secret.yaml:

yaml
123456789
apiVersion: v1
kind: Secret
metadata:
  name: db-passwords
type: Opaque
data:
  # In terminal, run: echo -n "supersecret" | base64
  # Output: c3VwZXJzZWNyZXQ=
  DB_PASS: c3VwZXJzZWNyZXQ= 

6. Injecting into Pods

Once a ConfigMap or Secret exists in the cluster, you must tell your Deployment how to inject it into the Pods.

Method 1: Environment Variables

yaml
123456789101112131415
# Inside your Deployment spec...
containers:
- name: my-app
  image: my-app:v1
  env:
    - name: APP_COLOR
      valueFrom:
        configMapKeyRef:
          name: app-config
          key: APP_COLOR
    - name: DATABASE_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-passwords
          key: DB_PASS

Method 2: Volume Mounts Instead of Environment Variables, you can mount the Secret so it appears as a physical file inside the container (e.g., /etc/secrets/DB_PASS.txt). This is highly preferred for massive configuration files or SSL certificates.

7. Mini Project: Secure Application Configuration

Let's decouple configuration from a deployment.

Step-by-Step Tutorial:

  1. 1. Save the configmap.yaml from Section 4 and secret.yaml from Section 5.
  1. 2. Apply them to your cluster:

bash
12
kubectl apply -f configmap.yaml
kubectl apply -f secret.yaml
  1. 3. Verify they exist:
bash
12
kubectl get configmaps
kubectl get secrets
  1. 4. Now, create a Pod that utilizes them (pod-test.yaml):
yaml
1234567891011121314151617181920
apiVersion: v1
kind: Pod
metadata:
  name: test-pod
spec:
  containers:
  - name: test-container
    image: alpine
    command: ['sh', '-c', 'echo "Color is $APP_COLOR and Pass is $DATABASE_PASSWORD" && sleep 3600']
    env:
      - name: APP_COLOR
        valueFrom:
          configMapKeyRef:
            name: app-config
            key: APP_COLOR
      - name: DATABASE_PASSWORD
        valueFrom:
          secretKeyRef:
            name: db-passwords
            key: DB_PASS
  1. 5. Apply the Pod: kubectl apply -f pod-test.yaml
  1. 6. Prove the injection worked by reading the Pod's logs:
bash
1
kubectl logs test-pod

*(You will see the output: "Color is blue and Pass is supersecret" !)*

8. Real-World Scenarios

A company deploys the exact same Docker Image of their API to a Staging Cluster and a Production Cluster. The image code is identical. However, the Staging Cluster has a ConfigMap setting ENVIRONMENT=STAGING, and the Production Cluster has a ConfigMap setting ENVIRONMENT=PRODUCTION. The application code reads this variable at runtime and behaves accordingly.

9. Best Practices

  • Never Commit Secrets to Git: While it is standard practice to commit configmap.yaml to GitHub, you should NEVER commit secret.yaml containing real production passwords, even if they are Base64 encoded. (Base64 is an encoding format, NOT encryption!). Use tools like "Sealed Secrets" or AWS Secrets Manager integration for GitOps workflows.

10. Common Mistakes

  • Base64 Newline Errors: When manually generating Base64 strings in the terminal, beginners often forget the -n flag (echo -n "secret" | base64). Without -n, the terminal encodes a hidden "newline" character at the end of the password. When the database tries to read the password, it fails authentication because it reads secret\n instead of secret.

11. Exercises

  1. 1. What is the fundamental difference in purpose between a ConfigMap and a Secret?
  1. 2. Explain the difference between injecting a Secret as an Environment Variable versus mounting it as a Volume.

12. FAQs

Q: Are Kubernetes Secrets actually secure? A: By default, they are just Base64 encoded flat files stored in etcd. They are NOT heavily encrypted by default! In a production cluster, the cluster administrator MUST enable "Encryption at Rest" for etcd, otherwise anyone with access to the master node's hard drive can read all the passwords in plain text.

13. Interview Questions

  • Q: Explain the 12-Factor App methodology regarding Configuration. How do Kubernetes ConfigMaps and Secrets facilitate adherence to this methodology?
  • Q: An auditor discovers a Kubernetes Secret YAML file containing production database credentials committed in plain text to a public GitHub repository. Outline the immediate incident response and the architectural changes required (e.g., External Secret Operators) to prevent recurrence.

14. Summary

In Chapter 8, we finalized our application decoupling strategy. We learned to externalize all mutable settings and sensitive credentials from our container images, ensuring our applications remain stateless and environment-agnostic. We utilized ConfigMaps to inject standard environment variables and deployed Kubernetes Secrets to safely pass Base64-encoded passwords to our Pods without exposing them in our primary Deployment manifests.

15. Next Chapter Recommendation

Our stateless applications are perfect. But what if we want to run a stateful Database that needs to permanently save data to a hard drive? Proceed to Chapter 9: Persistent Volumes and Storage.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·