// 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.
- Standard defaultsversion, network plugin, private cluster, feature flags per team and environment
- Computed defaultsnames and sizes derived from region and zone support
- Team overridesform values overwrite the defaults
- Network allocationfirst free block taken from a pool and marked allocated
- Lock set gatea locked flag stops later runs from overwriting customisations
- Terraform readone data source reads the secret; locals decode types, with safe defaults for optional keys
- Write-backoutputs such as cluster and identity ids are saved for later stages
- Change procedureread key and version, modify, write, plan; roll back via version history
- Offboardinglock reset and team removed from the registry so the name can be reused
// 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/andmetadata/access on the team prefix for the pipeline, and read-only for humans. - Python 3.10+ with
hvac, and Terraform with thehashicorp/vaultprovider. - The Vault CLI installed locally for the read-before-write procedure.
- Familiarity with Terraform type conversion functions and
try().
// Step-by-step implementation
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/andmetadata/separately; forgettingmetadata/is why list calls return empty.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 writesTrueby accident.03 Add the lock so customisations survive a re-run
The lock is itself a key:
standard_keys_population_locked. When it is the stringtrue, 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.
04 Decode by type in one locals block and fail loudly
In Terraform, build a single
team_valuesmap 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 usetry()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 totonumber; lists and objects are JSON strings passed tojsondecode; 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.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 blindputwith one field destroys every field you did not re-specify. Then run the stage withaction=Planand 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.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 thetry().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.
07 Write results back and reset state at offboarding
T5 keys are written by the onboarding root through a
vault_kv_secret_v2resource with afor_eachover a map of results, and consumed by later stages as ordinary reads. Using a stable_outputsuffix 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_cidrreturns a CIDR andvault kv metadata get <path>/vnet_cidrshows version history.- Set a key to a bad literal (for example
Truefor a boolean) in a scratch team and runterraform 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 planmust fail naming the key. - Roll back with
vault kv rollbackand 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 puton 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 meansvault kv listreturns nothing. - Sensitive-flag surprises: values read from Vault are sensitive in Terraform, so using them in
for_eachneedsnonsensitive()on the non-secret parts only. - Putting spaces after commas in CSV-style values.
a/32, b/32yields 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
- Wire this into the full chain with From Form to Running Cluster: Self-Service Team Onboarding.
- Make destructive operations safe with Demolition in Dependency Order: Safe, Re-runnable Offboarding.
- Move human edits behind review using Vault Access via Directory Groups, Requested by an Agent, Approved by a Human.