# Configuration: ConfigMaps and Secrets

Keep configuration out of images: ConfigMaps for settings, Secrets for credentials, how they reach containers, and why a Kubernetes Secret is encoded, not encrypted.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 6. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/06-configuration

## What you will learn

- Explain why configuration belongs outside the image
- Create a ConfigMap and a Secret and load them as environment variables
- Show that a Secret is only base64-encoded, and find where else its value leaks
- Name better options for real secrets, such as encryption at rest and an external secrets store

> **Lab status.** **Verified lab:** the ConfigMap, the Secret, decoding it, loading both into shop-web, and reading them back from a running Pod, on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** External Secrets Operator and KMS encryption (explained, not run). <br />**Cloud lab:** none needed; works on kind.

The same image should run in dev and prod; only the settings change. If the greeting, the colour or the
database address is baked into the image, every change means a new build. Kubernetes keeps settings in two
objects: **ConfigMaps** for ordinary settings and **Secrets** for credentials.

## ConfigMaps

```yaml
# 06-config.yaml (part 1)
apiVersion: v1
kind: ConfigMap
metadata:
  name: shop-config
data:
  GREETING: "Namaste from a ConfigMap"
  APP_COLOR: "#b23f1f"
```

A ConfigMap is just key-value data. A Pod can use it two ways:

- **As environment variables** (`envFrom` or `env.valueFrom`): simple, read once when the container starts.
- **As files** in a mounted volume: good for whole config files (an `nginx.conf`), and updated in the Pod
  eventually after you change the ConfigMap.

> **Figure.** Left: ConfigMap shop-config with keys GREETING and APP_COLOR, and Secret shop-secret with key DATABASE_URL, stored base64-encoded, not encrypted. Middle, route 1: envFrom with configMapRef shop-config turns keys into environment variables. Route 2: a volume of type secret with secretName shop-secret turns keys into files. Dashed arrows show either route works for either object. Right: Pod shop-web. Its environment, read once at start, holds GREETING=Namaste from a ConfigMap and APP_COLOR=#b23f1f and is frozen. Its files, mounted at /etc/creds, hold /etc/creds/DATABASE_URL, which the kubelet refreshes in place a minute or two after the Secret changes, never for subPath mounts.
>
> Two routes into a container. The lab used environment variables for both objects.

The lab loaded every key as an environment variable, then called the app:

```text
$ kubectl set env deployment/shop-web --from=configmap/shop-config
deployment.apps/shop-web env updated
$ kubectl run c --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://shop-web/api
{"version": "v1", "pod": "shop-web-55d49ccc4b-5xkmp", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 11}
```

The greeting changed without rebuilding the image. Note `uptime_seconds: 11`: changing the env meant a new
Pod template, so the Deployment rolled out new Pods. That's the rule to remember: **environment variables
are read only at start**. Edit a ConfigMap later and running Pods keep the old values until they restart,
for example with `kubectl rollout restart deployment/shop-web`.

> **Figure.** Animated. The Secret shop-secret is applied with a rotated password. Top lane, as an environment variable: the running Pod still shows DATABASE_URL old, because env is read only at start; then kubectl rollout restart deployment/shop-web runs, and a new Pod shows DATABASE_URL new. Bottom lane, as a mounted file: with no restart, the kubelet updates the file under /etc/creds to the new value a minute or two later; the app has to read the file again, and subPath mounts never update.
>
> The same change, two outcomes: env vars wait for new Pods, mounted files are updated in place.

## Secrets

A Secret looks almost the same. `stringData` lets you write the value in plain text, and Kubernetes stores it
base64-encoded:

```yaml
# 06-config.yaml (part 2)
apiVersion: v1
kind: Secret
metadata:
  name: shop-secret
type: Opaque
stringData:
  DATABASE_URL: "postgres://shop:S3cr3t-demo@db.internal:5432/shop"
```

Now look at what anyone with read access to Secrets sees:

```text
$ kubectl get secret shop-secret -o yaml
apiVersion: v1
data:
  DATABASE_URL: cG9zdGdyZXM6Ly9zaG9wOlMzY3IzdC1kZW1vQGRiLmludGVybmFsOjU0MzIvc2hvcA==
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Secret","metadata":{"annotations":{},"name":"shop-secret","namespace":"default"},"stringData":{"DATABASE_URL":"postgres://shop:S3cr3t-demo@db.internal:5432/shop"},"type":"Opaque"}
  ...
type: Opaque
$ kubectl get secret shop-secret -o jsonpath="{.data.DATABASE_URL}" | base64 -d
postgres://shop:S3cr3t-demo@db.internal:5432/shop
```

Two lessons in one output:

1. **base64 is not encryption.** One command decodes it.
2. **The password also sits in plain text in an annotation.** `kubectl apply` saves the manifest it applied in
   `last-applied-configuration`, `stringData` and all. Applying real secrets from files leaks them a second
   time.

Inside the Pod, it's an ordinary environment variable:

```text
$ kubectl set env deployment/shop-web --from=secret/shop-secret
deployment.apps/shop-web env updated
$ kubectl exec shop-web-55d49ccc4b-5xkmp -- printenv GREETING APP_COLOR DATABASE_URL
Namaste from a ConfigMap
#b23f1f
postgres://shop:S3cr3t-demo@db.internal:5432/shop
```

### Keeping real secrets safe

So why use Secrets at all? Because Kubernetes treats them differently from ConfigMaps: RBAC can grant
`get secrets` separately (lesson 8), they're kept in memory on nodes rather than on disk, and the API server can
encrypt them at rest.

> **Figure.** Top: the value postgres://shop:S3cr3t-demo@db.internal:5432/shop. Five places it shows up: 1, the YAML file, stringData in plain text, often committed to Git; 2, the Secret's data field, base64, one base64 -d away; 3, the last-applied-configuration annotation that kubectl apply stores, in plain text; 4, inside the Pod as an env var, shown by printenv and kubectl exec; 5, etcd, unencrypted unless encryption at rest is turned on. What to do: RBAC so very few people and service accounts may get secrets; KMS envelope encryption on EKS; an external store such as AWS Secrets Manager or Vault with the External Secrets Operator or the Secrets Store CSI Driver; and keeping real values out of Git.
>
> The lab found the password in the decoded data, the annotation and the Pod's environment.

For real credentials, go further:

- **Encryption at rest with KMS.** On EKS, envelope encryption with an AWS KMS key encrypts Secrets in etcd.
  (The course lab skipped it to save cost; production shouldn't.)
- **Least privilege.** Very few people and service accounts should be able to read Secrets.
- **An external secrets store.** Keep the real value in AWS Secrets Manager or Vault, and let the **External
  Secrets Operator** create the Kubernetes Secret, or mount it directly with the Secrets Store CSI Driver. The
  value then never lives in Git or in a manifest.
- **Never commit Secret manifests** with real values to Git, even private repositories.

## Mission: Change the app's behaviour without a rebuild

Create a ConfigMap with your own GREETING and APP_COLOR, and a Secret with a fake DATABASE_URL. Load both into shop-web, call /api to see the new greeting, decode the Secret, and find the second place its value appears in the Secret's YAML.

- You need: The shop-web Deployment and Service from lessons 4 and 5
- You'll have: ~/config.txt

```sh
$ kubectl apply -f 06-config.yaml
$ kubectl set env deployment/shop-web --from=configmap/shop-config --from=secret/shop-secret
$ kubectl rollout status deployment/shop-web
$ kubectl run c --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://shop-web/api > ~/config.txt
$ kubectl get secret shop-secret -o jsonpath="{.data.DATABASE_URL}" | base64 -d >> ~/config.txt
$ kubectl get secret shop-secret -o yaml | grep -c S3cr3t
```

The last command finds the plain-text password in the annotation. If the greeting doesn't change, the Pods
weren't restarted: check `kubectl rollout status`.

## Try it

- Apply the ConfigMap and Secret from this lesson and view them with `-o yaml`.
- Decode the Secret with `base64 -d`.
- Load both into the shop-web Deployment with `kubectl set env --from` and call `/api`.
- Run `kubectl exec <pod> -- printenv` and find the values.
- Do the mini mission and keep `~/config.txt`.

## Quiz

1. What protects the value inside a Kubernetes Secret by default?
   - Strong encryption
   - **Nothing more than base64 encoding and RBAC; anyone who can read the Secret can decode it** (answer)
   - A password only the API server knows
   Why: base64 is an encoding, not encryption. Protect Secrets with RBAC, encryption at rest (KMS on EKS) and, for real credentials, an external store.

2. You change a ConfigMap that a Deployment loads as environment variables. What happens to running Pods?
   - They pick up the new values instantly
   - **Nothing until the Pods are restarted; environment variables are read only at container start** (answer)
   - They crash
   Why: Restart the Deployment (kubectl rollout restart) or change the Pod template. Files mounted from a ConfigMap update eventually, but env vars never do.

3. Where did the plain-text database password also show up in the lab, besides the decoded Secret?
   - Nowhere
   - **In the last-applied-configuration annotation that kubectl apply stored on the Secret** (answer)
   - In the Pod's name
   Why: kubectl apply records the applied manifest, including stringData, in an annotation. Don't apply real secrets from files with stringData; use server-side apply or an external secrets tool.

## Resources

- [ConfigMaps](https://kubernetes.io/docs/concepts/configuration/configmap/) (Kubernetes)
- [Secrets](https://kubernetes.io/docs/concepts/configuration/secret/) (Kubernetes)
- [Good practices for Kubernetes Secrets](https://kubernetes.io/docs/concepts/security/secrets-good-practices/) (Kubernetes)
- [External Secrets Operator](https://external-secrets.io/) (External Secrets)
- [Envelope encryption of Kubernetes secrets on EKS](https://docs.aws.amazon.com/eks/latest/userguide/envelope-encryption.html) (AWS Docs)
