Workflow: Encrypted Before It Leaves Your Machine

How SOPS and age Work

age is a small encryption tool with a key pair: the public key (age1...) encrypts, the private key (AGE-SECRET-KEY-1..., in a file such as age.agekey) decrypts. Anyone may have the public key; whoever has the private key can read everything encrypted for it.

SOPS uses age to encrypt files that stay readable as YAML. It encrypts in two layers:

  1. it makes a random data key and encrypts every value with it (AES-256-GCM) - each value becomes ENC[AES256_GCM,data:...];
  2. it encrypts that data key for every recipient - every age public key the file is meant for - and stores the result in the sops: block at the end of the file.

To decrypt, SOPS opens the data key with a private key that matches one of the recipients, then the values with the data key. The two layers are why a rotation (below) needs two commands.

Which key, for which file - .sops.yaml at the root of the repository decides. Each rule has a path_regex, the age recipient for that path, and encrypted_regex: ^(data|stringData)$: only the values under data and stringData are encrypted. kind, metadata and the names of the keys stay readable, so a diff still shows that API_KEY in staging/payments-api changed - without showing it.

SOPS encryption policy

Show .sops.yaml
creation_rules:
  # Flux image automation deploy key (git push to this repo)
  - path_regex: flux/secrets/flux-system/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Cloudflare API token (cert-manager + external-dns)
  - path_regex: flux/secrets/cloudflare/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Auth secrets (Dex OIDC)
  - path_regex: flux/secrets/auth/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Observability secrets (shared)
  - path_regex: flux/secrets/observability/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Development environment secrets
  - path_regex: flux/secrets/develop/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Staging environment secrets
  - path_regex: flux/secrets/staging/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Production environment secrets
  - path_regex: flux/secrets/production/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ykac8h2lhgvppswhutsmsqu6cw0ht30wfjw9k7ghl6p8t5542y8s43zthp

  # Local (kind) profile - the learner's own key. Placeholder until
  # `scripts/sops-setup.sh --local` writes your public key here.
  - path_regex: flux/secrets/local/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1REPLACE_WITH_YOUR_PUBLIC_KEY_RUN_scripts_sops-setup.sh_--local

The platform paths (develop/, staging/, cloudflare/, …) are encrypted for the platform key. The last rule, flux/secrets/local/, holds your public key - Chapter 00 wrote it there with scripts/sops-setup.sh --local. Your cluster holds only your private key, so flux/secrets/local/ is the only folder it can decrypt; Flux applies it with the secrets-local Kustomization into develop.

In the cluster, the kustomize-controller reads the private key from the Secret flux-system/sops-age, decrypts in memory while it builds the folder, and applies normal Kubernetes Secrets. Terraform puts that key there through a write-only attribute (Chapter 02), so on the cloud cluster it is never stored in a plan or the state.

Where the Value Is Plaintext

SOPS protects Git. Everywhere else the value is plaintext, protected by something else - or by nothing:

WherePlaintext?What protects it
your editor while you write ityesthe helper writes the template into a private temp directory (mode 0700), outside the repository, and deletes it on exit
Git - every commit, every clone, every forkno - values are ENC[...]the private key, and the two checks below
the kustomize-controller while it buildsyes, in memorythe cluster
the Secret in developyes - base64 is an encodingRBAC: who may get secrets there. On Hetzner the everyday OIDC roles cannot read Secrets outside develop (Chapter 01)
the pod - environment or fileyeswho may exec into it, and what the application logs
age.agekey, sops-age, the kind Terraform statethe private key itselfgit-ignored file; RBAC on flux-system; the kind state is a local file (Chapter 02)

Two consequences. A kubectl get secret -o yaml pasted into a chat leaks the value as surely as a commit does. And a Secret changed in Git does not restart anything: a pod that reads it as an environment variable keeps the old value until it restarts.

Guardrails That Stop It

sops-encrypted - the check that matters here (workstation, CI). scripts/check-sops-encrypted.sh checks the secret manifests under flux/secrets/ - it skips kustomization.yaml/.yml files and *.example templates, which are not secrets - and refuses one that has no sops: block, or that has a value under data:/stringData: that is not ENC[...] - which catches a plaintext Secret, a base64 one, and a plaintext key added by hand to an encrypted file. It reads files only; it never decrypts and never prints a value.

check-sops-encrypted.sh

Show the sops-encrypted check
#!/usr/bin/env bash
set -Eeuo pipefail

cd "$(git rev-parse --show-toplevel)"

files=("$@")
if (( ${#files[@]} == 0 )); then
  while IFS= read -r f; do files+=("$f"); done < <(git ls-files 'flux/secrets/**.yaml' 'flux/secrets/**.yml')
fi
if (( ${#files[@]} == 0 )); then
  echo "sops-encrypted: no files to check."
  exit 0
fi

failed=0
checked=0
for f in "${files[@]}"; do
  # Only files under flux/secrets/ count; the manifests that wire them up and templates are skipped.
  case "$f" in
    flux/secrets/*) ;;
    *) continue ;;
  esac
  case "$(basename "$f")" in
    kustomization.yaml | kustomization.yml | *.example) continue ;;
  esac
  [[ -f "$f" ]] || continue
  checked=$((checked + 1))

  # No top-level sops: block means the whole file was never encrypted.
  if ! grep -q '^sops:' "$f"; then
    echo "NOT ENCRYPTED: $f has no SOPS metadata - encrypt it: sops --encrypt --in-place $f" >&2
    failed=1
    continue
  fi

  # Leaf values under the top-level data:/stringData: blocks must all be ENC[...].
  plain=$(awk -v q="'" '
    /^[^[:space:]#]/ {
      # YAML allows the key in quotes too: "stringData": is the same key as stringData:.
      in_block = ($0 ~ ("^[\"" q "]?(data|stringData)[\"" q "]?:"))
      # sops never writes an inline value here (`stringData: {token: x}`) - anything after the colon
      # other than a comment is plaintext the block scan below would not see. Only the key is
      # reported: the value itself must never reach a log (CI logs of this repository are public).
      if (in_block) {
        rest = $0; sub(/^[^:]+:[[:space:]]*/, "", rest)
        key = $0; sub(/:.*/, "", key); gsub("[\"" q "]", "", key)
        if (rest != "" && rest !~ /^#/) print "(inline value under " key ")"
      }
      next
    }
    in_block && /^[[:space:]]+[^[:space:]#][^:]*:/ {
      value = $0
      sub(/^[[:space:]]+[^:]+:[[:space:]]*/, "", value)
      if (value !~ /^ENC\[/) { key = $0; sub(/:.*/, "", key); gsub(/^[[:space:]]+/, "", key); gsub("[\"" q "]", "", key); print key }
    }
  ' "$f")
  if [[ -n "$plain" ]]; then
    echo "PLAINTEXT VALUE: $f - not encrypted: $(echo "$plain" | tr '\n' ' ')" >&2
    echo "  sops cannot decrypt a file with a plaintext value: delete those lines, then add the values with: sops edit $f" >&2
    failed=1
  fi
done

if (( failed )); then
  echo "Secrets under flux/secrets/ must be committed encrypted (see flux/secrets/README.md)." >&2
  exit 1
fi
echo "sops-encrypted: ${checked} secret file(s) checked, all encrypted."

It runs in two places, and they protect different things:

  • as a pre-commit hook, before the commit exists - the only check of every value under flux/secrets/ before it is published. git commit --no-verify skips it, which is exactly what Boris did;
  • in the Secrets guard CI job on every pull request and push to main. On the platform repository it is a required check: a pull request cannot merge into main without it - unless someone allowed to bypass the rule does (repository admins, and the image automation deploy key). It runs after the push, so it keeps the value out of main and the cluster, not out of public view.

GitHub’s push protection (GitHub) sits between the two: the platform repository has secret scanning with push protection on, so GitHub refuses a push that contains a token in a format it recognises - the API keys and tokens of many cloud and SaaS providers, GitHub’s own. It works even after --no-verify, because it runs on GitHub, not on your machine. It does not know your database password or an internal API key: a value without a known format passes it, so it adds to sops-encrypted, it does not replace it.

no-secrets (workstation, CI). scripts/block-secrets.sh refuses files by name: kubeconfigs, *.key, *.pem, *.agekey, credentials and .env files, Terraform state and plans. It is what keeps age.agekey out of Git even after git add -f. It does not look inside a YAML file - that is sops-encrypted’s job.

The helper - the easy path is the safe one (workstation). scripts/sops-encrypt-secret.sh <directory> <name> writes the Secret template outside the repository, opens it in your editor, encrypts it with the key .sops.yaml names for that directory, and writes only the encrypted file. It needs only the public key - Boris could have used it without the platform key.

Secret encryption helper

Show the secret encryption helper
#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

Create and encrypt a Kubernetes Secret with SOPS

ARGUMENTS:
    ENVIRONMENT     Target directory under flux/secrets/: develop, staging,
                    production, or local (the kind profile - encrypted with
                    your own key, see scripts/sops-setup.sh --local)
    SECRET_NAME     Name of the secret (e.g., backend-secrets)
    NAMESPACE       Namespace the Secret is created in (default: ENVIRONMENT,
                    or develop when ENVIRONMENT is local)

EXAMPLES:
    # Create encrypted secret for develop environment
    $0 develop backend-secrets

    # Create encrypted secret for production
    $0 production backend-secrets
    # Local kind profile: encrypted with your key, applied to develop
    $0 local lab-secret

WORKFLOW:
    1. Creates a plaintext secret template
    2. Opens it in \$EDITOR (or vi)
    3. After you save and quit, encrypts it with SOPS
    4. Saves encrypted version to flux/secrets/ENVIRONMENT/

NOTE:
    - Make sure .sops.yaml is configured with age public key
    - Make sure SOPS and age are installed
    - The plaintext file is automatically deleted after encryption

EOF
}

  # Validate environment
  if [[ ! -d "${secrets_dir}" ]]; then
    echo "❌ Invalid environment: ${env}"
    echo "   Available: develop, staging, production, local"
    exit 1
  fi

  # Check if secret already exists
  if [[ -f "${output_file}" ]]; then
    echo "⚠️  Secret already exists: ${output_file}"
    read -p "   Edit existing secret with SOPS? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
      sops --config "${REPO_ROOT}/.sops.yaml" edit "${output_file}"
      echo "✅ Secret updated"
      exit 0
    else
      exit 1
    fi
  fi

  # The plaintext never touches the repository: a private directory (mode 0700) per run, outside the
  # working copy, removed on every exit (Ctrl-C, cancel, failed encrypt). Global, not local: the
  # EXIT trap runs after this function has returned.
  work_dir="$(mktemp -d)"
  trap 'rm -rf "${work_dir}"' EXIT
  local temp_file="${work_dir}/${secret_name}.yaml"
  local encrypted_tmp="${work_dir}/${secret_name}.enc.yaml"

  # umask 077: the template (plaintext) is readable by you only.
  umask 077
  cat > "${temp_file}" <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: ${secret_name}
  namespace: ${namespace}
type: Opaque
stringData:
  # Add your secret keys here
  # Example:
  # database-url: "postgresql://user:pass@host:5432/db"
  # api-key: "your-api-key"
  # jwt-secret: "your-jwt-secret"

  # TODO: Replace with actual secret values
  example-key: "example-value"
EOF

  echo "📝 Created template: ${temp_file}"
  echo "   Opening in editor..."
  echo

  # Open in editor
  ${EDITOR:-vi} "${temp_file}"

  echo
  read -p "Encrypt this secret? (y/N): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Cancelled"
    exit 1
  fi

  # Encrypt with SOPS
  echo "🔐 Encrypting secret..."
  # --filename-override: the plaintext lives outside the repository, so tell sops which path it is
  # for - that picks the creation rule (and key) of flux/secrets/<env>/ in .sops.yaml.
  # Write to a temp name first: a failed encrypt must not leave an empty ${secret_name}.yaml behind.
  # --config: sops looks for .sops.yaml from the current directory; the script may run from anywhere.
  if ! sops --config "${REPO_ROOT}/.sops.yaml" --encrypt --filename-override "${output_file#"${REPO_ROOT}"/}" \
    --input-type yaml --output-type yaml \
    "${temp_file}" > "${encrypted_tmp}"; then
    echo "❌ Encryption failed - nothing written. Is your public key in .sops.yaml? (scripts/sops-setup.sh --local)"
    exit 1
  fi
  mv "${encrypted_tmp}" "${output_file}"

  echo "✅ Encrypted secret created: ${output_file}"
  echo
  echo "Next steps:"
  echo "  1. List it under resources: in ${secrets_dir}/kustomization.yaml:  - ${secret_name}.yaml"
  echo "  2. Commit both: git add ${output_file} ${secrets_dir}/kustomization.yaml && git commit -m 'Add ${secret_name} for ${env}'"
  echo "  3. Push: git push"
}

ENV="$1"
SECRET_NAME="$2"
NAMESPACE_ARG="${3:-}"

create_and_encrypt "${ENV}" "${SECRET_NAME}" "${NAMESPACE_ARG}"

sops-age belongs to Terraform (cluster). The key in the cluster is created by Terraform, never with kubectl: a Secret replaced by hand is invisible to Terraform, and the next rebuild brings the old key back. A key change is a plan a person reads, then an apply.

Safe Workflow (Step-by-Step)

Every command names its cluster with --context (Chapter 01).

  1. Create it encrypted. scripts/sops-encrypt-secret.sh local lab-secret - on the platform, develop/staging/production instead of local. To change an existing file, sops edit <file>; never a text editor - one plaintext value and sops refuses to decrypt the whole file.
  2. Check what you commit. Stage the Secret and the kustomization.yaml (git add), then git diff --cached shows ENC[...] for every value, and pre-commit run sops-encrypted --files <file> on the staged Secret passes. Once the hooks are installed (make install-hooks, Chapter 05), git commit runs that check by itself. Never --no-verify.
  3. Wire it. List the file under resources: in the folder’s kustomization.yaml. If you changed a value that a running pod reads, restart that reader in the same commit: a pod reads a Secret’s environment variables only at start. Run date -u +%FT%TZ and set the annotation safeops.io/secrets-rotated on the reader’s pod template to what it prints (the backend has it in flux/apps/backend/<env>/kustomization.yaml) - a changed template makes Flux roll the pods. Commit and push.
  4. Watch it arrive. flux --context kind-sre-control-plane reconcile kustomization secrets-local -n flux-system --with-source --timeout=2m, then kubectl --context kind-sre-control-plane -n develop get secret lab-secret - existence, not values.
  5. Watch the readers restart, when step 3 changed their annotation: kubectl --context kind-sre-control-plane -n develop rollout status deployment/<name>. Not kubectl rollout restart instead: on a Deployment Flux manages, Flux removes the annotation that command adds, and if that happens mid-rollout the old pods stay with the old value (Chapter 21).

Rotation

Three different situations - do not mix them up.

A value leaked (the incident): revoke it and issue a new one at its source, then sops edit the file (or create it with the helper) with the new value, commit, push, restart what reads it. The age key is fine; nothing else changes.

Routine rotation of the age key - the key is not known to be leaked, and nobody who held it has lost the right to read the secrets: the key is simply old, or due for its scheduled rotation. Someone who held it leaving is not routine - they keep a copy (see below). The goal is that the old key opens nothing written after the rotation.

  1. A new key, and both in the cluster for the transition. An age key file may hold several private keys. Put the new one first and the old one second, and send the file to the cluster: on kind, make kind-plan - the plan shows one in-place update of kubernetes_secret_v1.sops_age, never the key itself - then make kind-apply. Until every file is re-encrypted, Flux needs the old key too.

  2. The new public key into .sops.yaml - scripts/sops-setup.sh --local registers the first key in the file.

  3. Re-encrypt every file, both layers:

    • sops updatekeys -y <file> encrypts the data key for the recipients .sops.yaml names now. The values do not change - byte for byte;
    • sops rotate -i <file> makes a new data key and re-encrypts every value with it.

    updatekeys alone is not a rotation. Whoever holds the old key can take an old commit, open its data key - and that is still the data key of the current file, and of every value a later sops edit adds.

  4. Commit, push, reconcile - secrets-local is READY True again, now on files only the new key opens.

  5. Drop the old key from the file and apply again. Delete the old key file.

On Hetzner the same steps run with the platform key, passed as TF_VAR_sops_age_key, with sops_age_key_revision raised for each apply (Chapter 02). On kind the revision follows the key file, so there is no number to raise.

The age key leaked - or someone who held it left: the routine rotation and every value it protected replaced at its source, and the person’s own access removed. The new key closes the future; the old key still opens every old version that was encrypted for it. This is what the platform did on 2026-09-26.

Instructions for Your AI Agent

The rules this chapter adds. Two of them are enforced before anything is published; the rest are instructions.

  1. A new secret is created only with scripts/sops-encrypt-secret.sh - or sops edit for an existing file - never written in plaintext, never added to an encrypted file with a text editor. Enforced by: the sops-encrypted pre-commit hook, before the push; the Secrets guard CI job, before the merge - a pushed branch is already public.
  2. Never git commit --no-verify. Enforced by: nothing before the push - instruction only. CI repeats the checks after it.
  3. Never read, print, copy or commit a private key (*.agekey); never print decrypted values (sops -d, kubectl get secret -o yaml) into a chat or a log. Enforced by: committing - .gitignore, the no-secrets hook and CI. Reading and printing - instruction only.
  4. Never create, edit or delete flux-system/sops-age with kubectl - Terraform owns it on both clusters. On kind a key change is make kind-plan, read by a person, then make kind-apply. On Hetzner it is a pull request that raises the default of sops_age_key_revision (the key itself, the GitHub secret SOPS_AGE_KEY, is changed by a person), and the apply runs only after a person approves its plan. Enforced by: instruction only on kind. On Hetzner the OIDC roles cannot write Secrets in flux-system, and the apply job waits for approval in the environment production.
  5. A value that may have leaked: stop and report. Revoking it at its source and replacing it is a person’s decision. Enforced by: instruction only.

The full list, chapter by chapter, is docs/agent-rules.md in your fork of the platform repository.


This builds on: GitOps (Chapter 03) - secrets travel through the same Git path as everything else, and secrets-local is the Kustomization that decrypts them. This enables: CI/CD guardrails (Chapter 05) - the sops-encrypted hook and the Secrets guard job are one layer of the checks that every change passes before it is merged.