agentleFS
mattstrublemattstruble/skills/k8s-storage/SKILL.md

k8s-storage

Skill2 starsChanged 4 months agoMITView on GitHub

Use when working with Kubernetes ConfigMaps, Secrets, PersistentVolumes, PersistentVolumeClaims, or StorageClasses. Also trigger on volume mounts vs env vars decisions, handling ConfigMap/Secret updates (rollout restart, hash-based naming), access mode selection (RWO/ROX/RWX), choosing between Deployment+PVC and StatefulSet+volumeClaimTemplates, dynamic provisioning, or planning backup strategies for cluster state and persistent data. NOT for cluster setup (see k3s), Deployments/Services (see k8s-workloads), networking/ingress (see k8s-networking), Helm (see helm), or rollout strategies (see k8s-operations).

  • Reads credentials

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 3 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Rule: When in doubt, use a Secret.

    line 23
  2. Distinctive:

    When a ConfigMap or Secret changes, running Pods do not automatically pick up the new values:

    line 113
  3. Very specific:

    Default StorageClass: Only one should have storageclass.kubernetes.io/is-default-class: "true".

    line 164
  4. Very specific:

    Use when multiple Pods share the same volume.

    line 191
  5. Very specific:

    Use when each Pod needs its own independent volume (databases, per-instance state).

    line 253
  6. Distinctive:

    General recommendation: Use Velero writing to S3-compatible storage.

    line 355

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

k8s-storage

Patterns and decisions for ConfigMaps, Secrets, and persistent storage in self-hosted Kubernetes clusters.


ConfigMap vs Secret

SituationUse
Non-sensitive config (ports, feature flags, proxy settings)ConfigMap
Anything sensitive (passwords, API keys, tokens, TLS certs, DB connection strings)Secret
Binary data (font files, BSON files, compiled templates)ConfigMap binaryData or Secret (auto-base64)
Shared config file content (nginx.conf, app.yaml)ConfigMap data with multiline | block

Rule: When in doubt, use a Secret. Secrets can be encrypted at rest; ConfigMaps cannot. The only cost is base64 encoding, which is trivial.


ConfigMap YAML

apiVersion: v1
kind: ConfigMap
metadata:
  name: chlabs-io-config
data:
  PORT: "12345"                  # numbers must be quoted — data field is strings only
  MULTILINE_DATA: |
    Hello World!
    This is a multiline data.
binaryData:
  HELLO_WORLD: SGVsbG8sIFdvcmxkIQ==   # base64-encoded binary; decoded automatically when volume-mounted

Limits: Total size < 1 MB (keys + values). Name ≤ 253 chars, lowercase alphanumeric + - + ..


Secret YAML (Opaque)

# Create from .env file (most common)
kubectl create secret generic app.secret.env \
  --from-env-file=.env \
  --namespace=production
secret/app.secret.env created

# Inspect without revealing values
kubectl describe secret app.secret.env -n production

# Decode a specific key
kubectl get secret app.secret.env -n production -o json \
  | jq '.data | map_values(@base64d)'

Secret types: Opaque (generic), kubernetes.io/tls (TLS certs), kubernetes.io/dockerconfigjson (registry auth), kubernetes.io/ssh-auth, kubernetes.io/basic-auth.

Warning: Secrets are stored unencrypted in etcd by default. Enable encryption at rest for production clusters. Any user who can create a Pod in a namespace can read all Secrets in that namespace.


Env Vars vs Volume Mounts

ApproachUse whenCaveat
envFrom (ConfigMap)Simple key=value config, app reads env varsValues not updated at runtime; binaryData arrives base64-encoded
envFrom (Secret)Convenient but less secureEnv vars visible in crash dumps, /proc, and docker inspect
Volume mount (Secret)Files, multi-line data, TLS certs, SSH keysMore secure; each key becomes a file at mountPath/KEY
Volume mount (ConfigMap)Config files (nginx.conf, app.yaml)binaryData decoded automatically when mounted as file

Recommendation: Mount Secrets as volumes (readOnly: true). Use envFrom for ConfigMaps only when the app is designed to read env vars.

Pod consuming both (canonical pattern)

apiVersion: v1
kind: Pod
metadata:
  name: cm-secret-tester
spec:
  volumes:
    - name: secrets
      secret:
        secretName: app.secret.env
  containers:
    - name: app
      image: registry.k8s.io/busybox
      volumeMounts:
        - name: secrets
          readOnly: true
          mountPath: "/etc/secrets"   # each Secret key → /etc/secrets/<KEY>
      envFrom:
        - configMapRef:
            name: app.configmap       # all ConfigMap keys → env vars
      command: ["/bin/sh"]
      args: ["-c", "ls /etc/secrets && printenv"]

Selective keys: To mount only specific keys (or rename them), use items: under the secret: or configMap: volume definition.


Handling ConfigMap and Secret Updates

When a ConfigMap or Secret changes, running Pods do not automatically pick up the new values:

  • envFrom — never updates; env vars are set at container start
  • Volume mounts — files do update eventually (kubelet sync period, ~1 min), but most apps don't re-read files at runtime

Update strategies (pick one):

StrategyWhen to use
kubectl rollout restart deployment/<name>Small clusters, infrequent changes; simplest
Reloader controllerMid-size clusters; watches resources and triggers rolling restarts automatically
Hash-based naming (--append-hash)Large/complex clusters; forces workload update when config changes
Checksum annotation (Helm pattern)Helm-managed workloads; add checksum/config annotation to pod template

Hash-based naming:

# Creates configmap/app-config-<hash> — name changes when data changes
kubectl create configmap app-config --from-env-file=app.env --append-hash
# Update the Deployment to reference the new name → Pods restart automatically

Immutable resources (prevent accidental changes):

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config-v3
immutable: true   # prevents updates; must delete and recreate to change
data:
  KEY: value

StorageClass

A StorageClass is cluster-scoped and defines the provisioner, reclaim policy, and binding mode. Installed by the CSI driver.

# k3s default (local-path) — inspect with:
kubectl get storageclass local-path -o yaml

Key fields:

FieldOptionsNotes
provisionerrancher.io/local-path, csi.hetzner.cloud, driver.longhorn.ioSet by CSI driver install
reclaimPolicyDelete (default), RetainDefault is Delete — set Retain explicitly in production to prevent data loss when PVCs are deleted
volumeBindingModeWaitForFirstConsumer, ImmediateAlways use WaitForFirstConsumer — respects affinity/resource constraints
allowVolumeExpansiontrue, falseSet true for cloud volumes that support resize

Default StorageClass: Only one should have storageclass.kubernetes.io/is-default-class: "true". When a CSI driver installs its own StorageClass, verify it doesn't accidentally become the default.

Storage option comparison (self-hosted)

OptionIOPSFault toleranceSnapshotsRWXNotes
local-path (k3s default)Highest (NVMe direct)None (node-local)NoNoGood for dev, small DBs
Hetzner Cloud Volumes~70% of localNode-level (reattaches)Yes (CSI VolumeSnapshot)No~$5/TB/mo; needs podAffinity for RWO multi-pod
Longhorn~50% write, ~90% readMulti-node replicasYesYesBest for bare metal; needs 10 Gbps+ for good perf

Access Modes

ModeAbbreviationMeaning
ReadWriteOnceRWORead-write by Pods on one node
ReadOnlyManyROXRead-only by Pods on many nodes
ReadWriteManyRWXRead-write by Pods on many nodes simultaneously
ReadWriteOncePodRWOPRead-write by one Pod only (stricter than RWO)

Most cloud block storage (EBS, Hetzner Cloud Volumes) only supports RWO. If you need multiple Pods on different nodes to share a volume, use Longhorn (RWX) or co-locate Pods with podAffinity.


PVC: Standalone (Deployment pattern)

Use when multiple Pods share the same volume. Requires podAffinity if the StorageClass only supports RWO.

# 1. Create the PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc.hcloud-volumes
  namespace: misc
spec:
  storageClassName: hcloud-volumes
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
# 2. Deployment referencing the PVC — podAffinity co-locates Pods on same node (required for RWO)
# Use preferredDuringScheduling (soft) not requiredDuringScheduling (hard) to avoid first-deploy deadlock:
# hard self-referential affinity deadlocks — no node has an app=cache Pod yet, so all Pods stay Pending
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cache
  namespace: misc
spec:
  replicas: 5
  selector: { matchLabels: { app: cache } }
  template:
    metadata: { labels: { app: cache } }
    spec:
      affinity:
        podAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values: [cache]
                topologyKey: kubernetes.io/hostname   # prefer same node
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: pvc.hcloud-volumes
      containers:
        - name: app
          image: ubuntu:24.04
          volumeMounts:
            - name: data
              mountPath: /etc/data

Tip: If your StorageClass supports RWX (e.g., Longhorn), drop the podAffinity rule and Pods can spread across nodes for better fault tolerance.


PVC: StatefulSet with volumeClaimTemplates

Use when each Pod needs its own independent volume (databases, per-instance state). Each Pod gets a dedicated PVC named <template-name>-<statefulset-name>-<ordinal> (e.g., data-cache-0, data-cache-1).

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: cache
  namespace: misc
spec:
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: hcloud-volumes
        resources: { requests: { storage: 10Gi } }
  selector: { matchLabels: { app: cache } }
  template:
    metadata: { labels: { app: cache } }
    spec:
      containers:
        - name: app
          image: ubuntu:24.04
          volumeMounts:
            - name: data
              mountPath: /etc/data

No podAffinity needed — each Pod has its own PVC, so they can schedule independently on different nodes.

Deployment+PVC vs StatefulSet+volumeClaimTemplates

Deployment + PVCStatefulSet + volumeClaimTemplates
Volume sharingAll Pods share one volumeEach Pod gets its own volume
SchedulingMust co-locate (RWO) or use RWXPods can spread across nodes
IdentityPods are interchangeablePods have stable names (cache-0, cache-1)
Use caseShared cache, shared uploadsDatabases, per-instance state
PVC lifecycleManual; survives Deployment deleteAuto-created; not auto-deleted with StatefulSet

PVC cleanup: kubectl delete statefulset cache does not delete the PVCs. Delete them explicitly after verifying:

kubectl get pvc -n misc | grep cache   # verify which PVCs will be deleted
kubectl delete pvc data-cache-0 data-cache-1 data-cache-2 -n misc   # delete by name, not label

Avoid kubectl delete pvc -l app=cache — label-based bulk delete affects all PVCs with that label across all StatefulSets in the namespace.


kubectl Storage Commands

# PVCs (namespaced)
kubectl get pvc -n <namespace>
kubectl describe pvc <name> -n <namespace>
kubectl delete pvc <name> -n <namespace>   # WARNING: irreversible if reclaimPolicy=Delete — verify with kubectl get pv first

# PVs (cluster-scoped)
kubectl get pv
kubectl describe pv <name>

# StorageClasses (cluster-scoped)
kubectl get storageclass
kubectl get storageclass <name> -o yaml

# Expand a PVC (StorageClass must have allowVolumeExpansion: true)
kubectl patch pvc <name> -n <namespace> \
  -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'

Backup Strategy

Two categories require backup: cluster datastore and PersistentVolume data.

Cluster datastore (k3s)

DatastoreBackup approach
SQLite (single-node default)Stop k3s first (systemctl stop k3s), then copy /var/lib/rancher/k3s/server/db/ — live copies of SQLite WAL files may be corrupt. Or use sqlite3 state.db ".backup /tmp/k3s-backup.db" for online backup.
External DB (PostgreSQL/MySQL)Standard DB backup procedures
Embedded etcd (recommended)k3s etcd-snapshot — auto-runs daily at 00:00 and 12:00, retains 5 snapshots (~2.5 days); increase --etcd-snapshot-retention (e.g., 14–30) and enable S3 upload for production
# On-demand etcd snapshot
k3s etcd-snapshot save --name manual-$(date +%Y%m%d)

# Upload to S3 automatically (add to k3s server flags)
--etcd-s3 --etcd-s3-bucket=my-backup-bucket --etcd-s3-region=us-east-1

Critical: Save /var/lib/rancher/k3s/server/token — etcd data is encrypted with this token. Without it, snapshots cannot be restored.

PersistentVolume data

StrategyUse when
App-level dump (pg_dump, tar, rsync)Need application-consistent or format-specific backup (e.g., pg_dump for PostgreSQL version upgrades); or when storage snapshots are unavailable
Storage system snapshots (Longhorn, AWS EBS)General-purpose data; automate via storage UI or CronJob
VeleroFull cluster backup + PV data; supports migration and disaster recovery

General recommendation: Use Velero writing to S3-compatible storage. Store backups on a different system than the source data (different provider or region). Periodically test restores — untested backups are not backups.

# Velero backup (after installation)
velero backup create my-backup --include-namespaces production
velero restore create --from-backup my-backup

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.