Platform · Config as data

Vault as the Control Plane: A Five-Tier Key Model with Locking

All onboarding configuration lives in Vault as typed keys layered from defaults to overrides to computed values, with a lock that protects customisations from re-runs.

  • HashiCorp Vault KV v2
  • Python
  • Terraform
  • GitHub Actions

// Why this matters

A Vault KV v2 configuration model for Terraform sounds like over-engineering until the third time two systems write the same setting. In a self-service platform, configuration arrives from a form, from standard defaults, from a Python script that computes network blocks, from operators making a live fix, and from Terraform itself writing back cluster ids. If all of those write one undifferentiated store, nobody can answer the question "why is this value what it is, and will my edit survive the next run?"

Treating configuration as typed, versioned, layered data gives the platform a control plane that is separate from the code. Terraform becomes a pure function of the keys, the pipeline becomes a way of populating those keys, and an operator can change one value, plan, and roll back by version number without a pull request to the infrastructure code.

This post is the data model behind From Form to Running Cluster: Self-Service Team Onboarding. It covers the storage layout, the five tiers, the lock, the typing rules that bite, and the procedures for changing and adding keys safely.

// The problem

When defaults, form values, manual edits and computed values all write the same store, three things happen. Edits get overwritten by the next default sync, because the sync cannot tell a stale default from a deliberate customisation. Types get guessed: a boolean written as True instead of true silently falls back to a default and masks the change. And JSON-blob keys get destroyed by a blind put that re-specifies only one field.

The second problem is discoverability. If the only list of keys is the defaults file, operators assume it is complete. In practice dozens of keys are read by Terraform with a fallback, or written by the populator, and are never in that file. Without a model of where each key comes from, nobody knows which layer to edit, and the same fix has to be re-applied after every run.

The third problem is the blast radius of getting it wrong. Configuration drives cluster sizes, network ranges and feature flags. A silent default that produces a cluster of the wrong size is worse than a failed plan that names the missing key.

// The solution

Storage is deliberately flat: a KV v2 mount, a path per team and environment, and one secret per key, each holding a single field called value. Scalars are strings; structured settings are JSON strings in the same field. One secret per key gives every key its own version history, its own undelete, and its own audit line, which a single big JSON secret cannot.

The five tiers describe where a key comes from and how it survives a re-run. T1 standard defaults come from a CSV and are rewritten by the populator unless locked. T2 optional keys are read by Terraform through try() with a default and exist only if someone sets them. T3 hard-required keys are read bare and must exist. T4 computed keys (network blocks, ids, names) are written by the populator on every run. T5 are Terraform write-backs consumed by later stages. The model is documented, including its sharp edge: the lock protects T1 but not T4.

Types are decided where the key is consumed, never guessed. Vault stores everything as a string; Terraform decodes with tonumber, == "true", jsondecode or split. A short tracing recipe (grep the read, look at the decode) lets anyone derive the format of an unfamiliar key from source rather than from folklore.

Alternatives I rejected: a single JSON document per team (no per-key history, merge conflicts on concurrent writes), Terraform variable files in Git (changes need a code review for a data edit and secrets-adjacent values end up in the repo), and a database (another system to run and secure). KV v2 already gives versions, metadata, policies and audit.

How it flows flow1. Standard defaults → 2. Computed defaults → 3. Team overrides → 4. Network allocation → 5. Lock set → 6. Terraform read → 7. Write-back → 8. Change procedure → 9. Offboarding01Standard defaults02Computed defaults03Team overrides04Network allocation05 · GATELock set06Terraform read07Write-back08Change procedure09Offboarding
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Standard defaultsversion, network plugin, private cluster, feature flags per team and environment
  2. Computed defaultsnames and sizes derived from region and zone support
  3. Team overridesform values overwrite the defaults
  4. Network allocationfirst free block taken from a pool and marked allocated
  5. Lock set gatea locked flag stops later runs from overwriting customisations
  6. Terraform readone data source reads the secret; locals decode types, with safe defaults for optional keys
  7. Write-backoutputs such as cluster and identity ids are saved for later stages
  8. Change procedureread key and version, modify, write, plan; roll back via version history
  9. Offboardinglock reset and team removed from the registry so the name can be reused
T1 Standard defaultsCSV in GitOverwritten unless lockedT2 Optional / T3 RequiredT2: try() defaultT3: bare read, must existT4 ComputedCIDRs, names, idsRewritten every runT5 Write-backCluster idsIdentity client idsWritten by Terraform
The five key tiers. Each tier has a different writer and a different re-run behaviour; edit the right one.
Team CSVPopulatorVaultTerraformwrite T1 defaults unless lock=trueoverrides for this teamwrite overrides and T4 computed keysbulk read, decode by typewrite T5 result keys back
Key lifecycle across one onboarding. The populator writes before Terraform reads; Terraform writes back what later stages need.

// Before you start

  • Vault 1.12+ with a KV v2 mount and a CI auth method (JWT/OIDC from your CI, or a scoped token).
  • A policy that grants data/ and metadata/ access on the team prefix for the pipeline, and read-only for humans.
  • Python 3.10+ with hvac, and Terraform with the hashicorp/vault provider.
  • The Vault CLI installed locally for the read-before-write procedure.
  • Familiarity with Terraform type conversion functions and try().

// Step-by-step implementation

  1. 01 Lay out the store: one secret per key, one field called value

    Pick a path convention and never deviate: <mount>/<Env>/Teams/<team>-<env>/<key>. Each secret has a single field, value. This feels wasteful until you need to roll back one setting without touching 99 others.

    Write a policy that gives the pipeline identity create/update on the data and metadata paths for the team prefix and gives humans read plus the ability to write only to approved subpaths. Remember that KV v2 policies address data/ and metadata/ separately; forgetting metadata/ is why list calls return empty.

  2. 02 Write the populator: defaults, overrides, computed values, in that order

    The populator is a small Python program using hvac. It performs three passes in a fixed order so later passes win: standard defaults from the CSV, then the team CSV overrides, then computed keys. The order is the tiering; if you reorder it you change which writer wins.

    Make writes cheap and boring: a helper that writes one key as {"value": str(v)}. Convert booleans to lowercase strings in one place so nobody writes True by accident.

  3. 03 Add the lock so customisations survive a re-run

    The lock is itself a key: standard_keys_population_locked. When it is the string true, the populator skips the T1 pass. Set it at the end of the first successful onboarding so later edits stick. Treat any failure to read the key as "not locked", because on first run the key does not exist yet.

    Be honest about what it covers. It protects T1. Team CSV overrides (pass two) and computed keys (pass three) still run, so re-running the first stage resets keys that appear in the team CSV and recomputes derived values. If you need those to survive too, remove the key from the team CSV after onboarding rather than expecting the lock to do it.

  4. 04 Decode by type in one locals block and fail loudly

    In Terraform, build a single team_values map from the bulk read, then decode in one place. Required keys are accessed with plain indexing so a missing key aborts the plan and names the key. Optional keys use try() with a default you document next to the line.

    Know the per-type literals: booleans are lowercase strings compared with == "true"; integers are bare numeric strings passed to tonumber; lists and objects are JSON strings passed to jsondecode; comma lists are split with no spaces. Inside a JSON blob the types are native JSON, and they can be deliberately inconsistent (a version number as a string in one blob, a number in another), so copy a known-good value rather than typing one.

  5. 05 Change a key safely: read before write, capture the version, plan

    The change procedure is four commands. Read the key and capture its version. If it is a JSON blob, copy it to a file, edit that file, validate with jq -e, and write the whole document back; a blind put with one field destroys every field you did not re-specify. Then run the stage with action=Plan and read the plan before applying.

    Because every key is its own secret with versions, rollback is symmetric. Read the metadata to find the previous version, and either write the old value back or use vault kv rollback. Nothing about the change was in Git, so the version number is your audit anchor: write it in the change ticket.

  6. 06 Add a new key end to end without breaking existing teams

    A new setting touches four places and the order matters. First add the read in Terraform as T2 (with try() and a default that preserves current behaviour) and ship that, so existing teams plan clean. Second, add the default to the standard CSV so new teams get it. Third, backfill existing teams only if their behaviour should change. Fourth, once every team has the key, you may tighten it to T3 by removing the try().

    When you add a default to the CSV, remember the escaping: the value is column two, and JSON must be wrapped in double quotes with every inner quote doubled. A common review catch is a CSV that parses but yields a string with literal quotes.

  7. 07 Write results back and reset state at offboarding

    T5 keys are written by the onboarding root through a vault_kv_secret_v2 resource with a for_each over a map of results, and consumed by later stages as ordinary reads. Using a stable _output suffix keeps them visually separate from inputs and tells operators they will be overwritten on the next apply.

    At offboarding, clear the lock and remove the team from the registry so the name can be reused cleanly (see Demolition in Dependency Order: Safe, Re-runnable Offboarding). Without the reset, a re-created team inherits a locked state and never receives fresh defaults.

// How to verify it works

  • vault kv get -field=value <path>/vnet_cidr returns a CIDR and vault kv metadata get <path>/vnet_cidr shows version history.
  • Set a key to a bad literal (for example True for a boolean) in a scratch team and run terraform plan; confirm it either hard-fails or visibly takes the documented default, never a silent surprise.
  • Set the lock to true, edit a T1 key by hand, re-run the populator; the edit must survive. Edit a key that is in the team CSV and re-run; confirm it resets, proving the documented limit.
  • Remove a required key in a scratch team; terraform plan must fail naming the key.
  • Roll back with vault kv rollback and confirm the next plan returns to the previous result.

// Design decisions and trade-offs

  • Five tiers: standard CSV, team CSV, injected values, live edits, Terraform outputs. A key missing from the standard CSV is not missing from the system.
  • JSON-blob keys must be read before write, because a blind put destroys fields it does not re-specify.
  • Re-running the first stage resets team-CSV keys to their CSV values and re-locks; the lock does not protect the computed layer. This is documented, not hidden.
  • A missing required key fails the plan; there are no silent defaults.
  • Secrets are never in the repo or workflow; only generic path shapes are documented.

// Pitfalls and lessons learned

  • A blind vault kv put on a JSON blob. It replaces the secret with only the fields you passed. Always read, edit a file, validate, write the whole document.
  • Assuming the defaults CSV is the full key list. T2, T3 and T4 keys are not in it; trace the read in Terraform to find them.
  • Mixing types inside blobs. A version number may be a string in one blob and a number in another; copy a working value instead of retyping.
  • Treating the lock as a shield for everything. It stops T1 writes only; team-CSV keys and computed keys still reset on a stage-one re-run.
  • Forgetting metadata/ in the policy. data/ access alone means vault kv list returns nothing.
  • Sensitive-flag surprises: values read from Vault are sensitive in Terraform, so using them in for_each needs nonsensitive() on the non-secret parts only.
  • Putting spaces after commas in CSV-style values. a/32, b/32 yields a leading space and a broken CIDR.

// Frequently asked questions

Why one Vault secret per key instead of one JSON secret per team?

Per-key secrets give per-key version history, rollback and audit, and avoid lost updates when two writers touch different settings. A single JSON secret makes every edit a read-modify-write of the whole document.

How do I roll back a Vault KV v2 key?

Use vault kv rollback -version=N <path> or read the old version with -version=N and write it back. Deleted versions can be restored with vault kv undelete until destroyed.

How does Terraform know a key is a number or a boolean?

Vault stores strings. The consuming Terraform decodes with tonumber, a comparison to the string "true", jsondecode or split. Grep the read to see which one applies.

What does the lock key protect?

It stops the populator rewriting the standard-default tier. It does not protect team-CSV overrides or computed keys, by design and by documentation.

Can I read Vault configuration into Terraform with for_each?

Yes: list the secret names with vault_kv_secrets_list_v2, wrap with nonsensitive(), and for_each over the set to read each secret. Build one team_values map and decode from it.

// The outcome

Typed, versioned, rollback-able configuration for every environment, with 35+ standard keys per customer environment.

// Where to take it next

// Keep reading