Procházet zdrojové kódy

feat(settings): variables, examples and immutable keys (#53)

Step 2 of the stage 2 settings design. With default values the plan on both
live stacks is a no-op: no resource is renamed, replaced or modified, and the
rendered connector user_data is byte-identical (golden hashes taken on
origin/main).

- resource_key (names and tags, empty means region) and site_name (telemetry
  label only, in no name, tag or output)
- validations: region slug, vpc_ip_range network address and prefix,
  reserved_ranges overlap, reboot_times (distinct HH:MM), SSH key with an
  optional comment that is stripped before cloud-init
- terraform.tfvars.example for stacks 00 and 10, planned by a generated test
- scripts/plan_noop_check.py with golden address files, proven on mocked plans
- settings manifest, generated reference and a wiki lesson

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
ChiefGyk3D před 1 měsícem
rodič
revize
898cb90dd0
40 změnil soubory, kde provedl 3709 přidání a 135 odebrání
  1. 37 0
      docs/golden-addresses/00-foundation.json
  2. 130 0
      docs/golden-addresses/10-access.json
  3. 85 58
      docs/settings.json
  4. 1 1
      docs/wiki/Droplet-Hardening.md
  5. 1 0
      docs/wiki/Reading-Order.md
  6. 15 13
      docs/wiki/Settings-Reference.md
  7. 2 2
      docs/wiki/Terraform-Reference.md
  8. 98 0
      docs/wiki/Variables-Tfvars-and-Secrets.md
  9. 1 0
      docs/wiki/_Sidebar.md
  10. 4 1
      modules/firewall/main.tf
  11. 34 0
      modules/firewall/tests/firewall.tftest.hcl
  12. 11 0
      modules/firewall/variables.tf
  13. 10 1
      modules/twingate-bootstrap/main.tf
  14. 2 2
      modules/twingate-bootstrap/outputs.tf
  15. 294 2
      modules/twingate-bootstrap/tests/bootstrap.tftest.hcl
  16. 14 3
      modules/twingate-bootstrap/variables.tf
  17. 1 0
      modules/twingate-connector/main.tf
  18. 37 0
      modules/twingate-connector/tests/connector.tftest.hcl
  19. 12 1
      modules/twingate-connector/variables.tf
  20. 7 1
      modules/vpc/main.tf
  21. 35 0
      modules/vpc/tests/vpc.tftest.hcl
  22. 11 0
      modules/vpc/variables.tf
  23. 94 0
      scripts/gen_example_tests.py
  24. 112 18
      scripts/hcl_variables.py
  25. 255 0
      scripts/plan_noop_check.py
  26. 45 10
      stacks/00-foundation/main.tf
  27. 36 0
      stacks/00-foundation/terraform.tfvars.example
  28. 49 0
      stacks/00-foundation/tests/example.tftest.hcl
  29. 435 0
      stacks/00-foundation/tests/foundation.tftest.hcl
  30. 59 2
      stacks/00-foundation/variables.tf
  31. 21 14
      stacks/10-access/main.tf
  32. 57 0
      stacks/10-access/terraform.tfvars.example
  33. 446 2
      stacks/10-access/tests/access.tftest.hcl
  34. 77 0
      stacks/10-access/tests/example.tftest.hcl
  35. 71 2
      stacks/10-access/variables.tf
  36. 574 0
      tests/test_plan_noop_check.py
  37. 101 0
      tests/test_resource_key.py
  38. 66 2
      tests/test_settings_manifest.py
  39. 299 0
      tests/test_tfvars_example.py
  40. 70 0
      tests/test_unused_variables.py

+ 37 - 0
docs/golden-addresses/00-foundation.json

@@ -0,0 +1,37 @@
+{
+  "stack": "stacks/00-foundation",
+  "note": "Every resource address the stack has today, with the default settings (the values the live stack uses), and the attributes that force a replacement or hold identity. scripts/plan_noop_check.py fails a plan that changes any of them. '@unchanged' means only before == after (ids and sensitive values such as user_data). A pull request that adds a resource updates this file on purpose.",
+  "addresses": {
+    "digitalocean_project.this": {
+      "type": "digitalocean_project",
+      "force_new": {
+        "name": "clouds-against-humanity"
+      }
+    },
+    "digitalocean_tag.baseline": {
+      "type": "digitalocean_tag",
+      "force_new": {
+        "name": "cah-baseline-tor1"
+      }
+    },
+    "module.vpc.digitalocean_vpc.this": {
+      "type": "digitalocean_vpc",
+      "force_new": {
+        "name": "foundation-tor1-vpc",
+        "region": "tor1",
+        "ip_range": "10.78.0.0/24"
+      }
+    },
+    "module.baseline_firewall.digitalocean_firewall.this": {
+      "type": "digitalocean_firewall",
+      "force_new": {
+        "name": "foundation-tor1-baseline",
+        "tags": [
+          "cah-baseline-tor1"
+        ]
+      }
+    }
+  },
+  "data": [],
+  "moves": {}
+}

+ 130 - 0
docs/golden-addresses/10-access.json

@@ -0,0 +1,130 @@
+{
+  "stack": "stacks/10-access",
+  "note": "Every resource address the stack has today, with the default settings (the values the live stack uses), and the attributes that force a replacement or hold identity. scripts/plan_noop_check.py fails a plan that changes any of them. '@unchanged' means only before == after (ids and sensitive values such as user_data). A pull request that adds a resource updates this file on purpose.",
+  "addresses": {
+    "digitalocean_project_resources.access": {
+      "type": "digitalocean_project_resources",
+      "force_new": {
+        "project": "@unchanged",
+        "resources": "@unchanged"
+      }
+    },
+    "digitalocean_tag.connector": {
+      "type": "digitalocean_tag",
+      "force_new": {
+        "name": "cah-connector-tor1"
+      }
+    },
+    "module.connector_a.digitalocean_droplet.connector": {
+      "type": "digitalocean_droplet",
+      "force_new": {
+        "name": "access-tor1-connector-a",
+        "region": "tor1",
+        "size": "s-1vcpu-1gb",
+        "image": "ubuntu-24-04-x64",
+        "vpc_uuid": "@unchanged",
+        "tags": [
+          "cah-baseline-tor1",
+          "cah-connector-tor1"
+        ],
+        "ssh_keys": "@unchanged",
+        "user_data": "@unchanged",
+        "ipv6": false,
+        "backups": false,
+        "monitoring": true
+      }
+    },
+    "module.connector_a.module.bootstrap.twingate_connector.this": {
+      "type": "twingate_connector",
+      "force_new": {
+        "name": "access-tor1-connector-a",
+        "remote_network_id": "@unchanged"
+      }
+    },
+    "module.connector_a.module.bootstrap.twingate_connector_tokens.this": {
+      "type": "twingate_connector_tokens",
+      "force_new": {
+        "connector_id": "@unchanged"
+      }
+    },
+    "module.connector_b.digitalocean_droplet.connector": {
+      "type": "digitalocean_droplet",
+      "force_new": {
+        "name": "access-tor1-connector-b",
+        "region": "tor1",
+        "size": "s-1vcpu-1gb",
+        "image": "ubuntu-24-04-x64",
+        "vpc_uuid": "@unchanged",
+        "tags": [
+          "cah-baseline-tor1",
+          "cah-connector-tor1"
+        ],
+        "ssh_keys": "@unchanged",
+        "user_data": "@unchanged",
+        "ipv6": false,
+        "backups": false,
+        "monitoring": true
+      }
+    },
+    "module.connector_b.module.bootstrap.twingate_connector.this": {
+      "type": "twingate_connector",
+      "force_new": {
+        "name": "access-tor1-connector-b",
+        "remote_network_id": "@unchanged"
+      }
+    },
+    "module.connector_b.module.bootstrap.twingate_connector_tokens.this": {
+      "type": "twingate_connector_tokens",
+      "force_new": {
+        "connector_id": "@unchanged"
+      }
+    },
+    "module.connector_firewall.digitalocean_firewall.this": {
+      "type": "digitalocean_firewall",
+      "force_new": {
+        "name": "access-tor1-connector",
+        "tags": [
+          "cah-connector-tor1"
+        ]
+      }
+    },
+    "twingate_group.admins": {
+      "type": "twingate_group",
+      "force_new": {
+        "name": "cah-tor1-admins"
+      }
+    },
+    "twingate_remote_network.this": {
+      "type": "twingate_remote_network",
+      "force_new": {
+        "name": "access-tor1",
+        "location": "OTHER"
+      }
+    },
+    "twingate_resource.connector_a_ssh": {
+      "type": "twingate_resource",
+      "force_new": {
+        "name": "cah-tor1-connector-a-ssh",
+        "address": "@unchanged",
+        "remote_network_id": "@unchanged"
+      }
+    },
+    "twingate_resource.connector_b_ssh": {
+      "type": "twingate_resource",
+      "force_new": {
+        "name": "cah-tor1-connector-b-ssh",
+        "address": "@unchanged",
+        "remote_network_id": "@unchanged"
+      }
+    }
+  },
+  "data": [
+    "data.digitalocean_ssh_key.admin"
+  ],
+  "moves": {
+    "module.connector_a.twingate_connector.this": "module.connector_a.module.bootstrap.twingate_connector.this",
+    "module.connector_a.twingate_connector_tokens.this": "module.connector_a.module.bootstrap.twingate_connector_tokens.this",
+    "module.connector_b.twingate_connector.this": "module.connector_b.module.bootstrap.twingate_connector.this",
+    "module.connector_b.twingate_connector_tokens.this": "module.connector_b.module.bootstrap.twingate_connector_tokens.this"
+  }
+}

+ 85 - 58
docs/settings.json

@@ -6,31 +6,29 @@
       {
         "name": "region",
         "type": "string",
-        "description": "DigitalOcean region slug.",
+        "description": "DigitalOcean region slug. Names are built from resource_key, which defaults to this. Check the sizes your account may use in the region (GET /v2/sizes) before changing it.",
         "required": false,
         "default": "tor1",
-        "validation": "none today (planned: pattern check)",
+        "validation": "^[a-z]{3}[0-9]$ (three lowercase letters and a digit); the pattern cannot know which sizes the account may use",
         "set_where": "tfvars (local plans) or Spacelift stack environment (TF_VAR_*)",
         "example": "tor1",
         "sensitivity": "public",
         "sensitive_in_code": false,
-        "status": "exists",
-        "planned_change": "Regex validation for the region slug; the description should say to check the account's available sizes first."
+        "status": "exists"
       },
       {
         "name": "vpc_ip_range",
         "type": "string",
-        "description": "Private CIDR. Must not overlap any homelab range (confirmed in the stage 0 guide before apply).",
+        "description": "Private CIDR for the VPC. Must be the network address and must not overlap any range in reserved_ranges.",
         "required": false,
         "default": "10.78.0.0/24",
-        "validation": "none in the stack; modules/vpc checks it is a private IPv4 CIDR (10/8, 172.16/12, 192.168/16)",
+        "validation": "private IPv4 CIDR (10/8, 172.16/12, 192.168/16, also checked in modules/vpc); the network address (10.78.0.0/24, not 10.78.0.5/24); prefix length between /16 and /28; no overlap with reserved_ranges (a precondition on the project, because OpenTofu 1.8 cannot compare two variables in a validation)",
         "set_where": "tfvars (local plans) or Spacelift stack environment (TF_VAR_*)",
         "example": "10.99.0.0/24",
         "sensitivity": "private",
         "sensitive_in_code": false,
         "status": "exists",
-        "readers": "UNVERIFIED: Doppler config members and Spacelift stack environment readers; filled in during step 2",
-        "planned_change": "Prefix length between /16 and /28, and no overlap with reserved_ranges."
+        "readers": "UNVERIFIED: Doppler config members and Spacelift stack environment readers; filled in during step 2"
       },
       {
         "name": "project_name",
@@ -48,21 +46,21 @@
       {
         "name": "reserved_ranges",
         "type": "list(string)",
-        "description": "Ranges you connect to (home networks); vpc_ip_range must not overlap them.",
+        "description": "Private CIDRs the VPC range must not overlap (your homelab, other VPCs). Optional; they identify your network, so they are never committed. Prompts the human check, does not replace it.",
         "required": false,
         "default": [],
-        "validation": "each entry a valid CIDR; vpc_ip_range must not overlap any entry",
-        "set_where": "Doppler or private tfvars (identifies the owner's network)",
+        "validation": "each entry an IPv4 CIDR; vpc_ip_range must not overlap any entry (compared by first and last address)",
+        "set_where": "Spacelift stack environment (TF_VAR_reserved_ranges, a JSON list) or a private tfvars today; Doppler only once a hook line in .spacelift/config.yml requests it (the foundation hooks request only DIGITALOCEAN_TOKEN)",
         "example": "[\"10.50.0.0/16\", \"10.60.0.0/16\"]",
         "sensitivity": "private",
         "sensitive_in_code": true,
-        "status": "planned",
+        "status": "exists",
         "readers": "UNVERIFIED: Doppler config members and Spacelift stack environment readers; filled in during step 2"
       },
       {
         "name": "resource_key",
         "type": "string",
-        "description": "Key used in resource names instead of region; empty means region.",
+        "description": "Key used in the names and tags of cloud and Twingate objects instead of region; empty means region, so every name is identical to a stack that never set it. IMMUTABLE for the life of a stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name.",
         "required": false,
         "default": "",
         "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$; immutable on a live stack",
@@ -70,20 +68,20 @@
         "example": "tor1",
         "sensitivity": "public",
         "sensitive_in_code": false,
-        "status": "planned"
+        "status": "exists"
       },
       {
         "name": "site_name",
         "type": "string",
-        "description": "Telemetry label for the site; empty means site-<region>. In no resource name or tag.",
+        "description": "Telemetry label for the site (metrics and log labels in a later stage); empty means site-<region>. In no resource name, tag or output; changing it replaces nothing.",
         "required": false,
         "default": "",
-        "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$; unique across sites",
+        "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$; unique across sites (a rule for the person, one stack cannot test it)",
         "set_where": "tfvars (local plans) or Spacelift stack environment (TF_VAR_*)",
         "example": "site-tor1",
         "sensitivity": "public",
         "sensitive_in_code": false,
-        "status": "planned"
+        "status": "exists"
       },
       {
         "name": "provider_name",
@@ -103,9 +101,9 @@
       {
         "name": "region",
         "type": "string",
-        "description": "DigitalOcean region slug, the same value as stack 00 (the code has no description for it).",
+        "description": "DigitalOcean region slug, from the foundation stack's region output. Names are built from resource_key, which defaults to this.",
         "required": true,
-        "validation": "none today",
+        "validation": "^[a-z]{3}[0-9]$ (three lowercase letters and a digit)",
         "set_where": "Spacelift stack dependency, mapped to a TF_VAR_* environment variable (output of stack 00)",
         "example": "tor1",
         "sensitivity": "public",
@@ -164,9 +162,9 @@
       {
         "name": "admin_ssh_public_key",
         "type": "string",
-        "description": "Public SSH key for the cah-admin user on the connectors (the stack has no description; modules/twingate-bootstrap requires type and key with no comment).",
+        "description": "Public SSH key for the cah-admin user on the connectors: '<algorithm> <key>' with an optional trailing comment of one word. The comment is dropped before cloud-init, so user_data does not depend on it.",
         "required": true,
-        "validation": "none in the stack (the bootstrap module requires '<ssh-ed25519|ssh-rsa> <key>' with no comment); planned: accept a trailing comment",
+        "validation": "^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)) [A-Za-z0-9+/]+=*( [A-Za-z0-9@._+:=/-]{1,64})?$ (one optional comment word of safe characters; no line break or other whitespace); the same check in modules/twingate-bootstrap",
         "set_where": "Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (ADMIN_SSH_PUBLIC_KEY)",
         "example": "ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY",
         "sensitivity": "private",
@@ -203,7 +201,7 @@
       {
         "name": "resource_key",
         "type": "string",
-        "description": "Key used in resource names instead of region; empty means region.",
+        "description": "Key used in the names and tags of cloud and Twingate objects instead of region; empty means region, so every name is identical to a stack that never set it. IMMUTABLE for the life of a stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name.",
         "required": false,
         "default": "",
         "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$; immutable on a live stack",
@@ -211,12 +209,12 @@
         "example": "tor1",
         "sensitivity": "public",
         "sensitive_in_code": false,
-        "status": "planned"
+        "status": "exists"
       },
       {
         "name": "site_name",
         "type": "string",
-        "description": "Telemetry label for the site; empty means site-<region>.",
+        "description": "Telemetry label for the site (metrics and log labels in a later stage); empty means site-<region>. In no resource name, tag or output; changing it replaces nothing.",
         "required": false,
         "default": "",
         "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$",
@@ -224,7 +222,7 @@
         "example": "site-tor1",
         "sensitivity": "public",
         "sensitive_in_code": false,
-        "status": "planned"
+        "status": "exists"
       },
       {
         "name": "provider_name",
@@ -242,15 +240,18 @@
       {
         "name": "reboot_times",
         "type": "map(string)",
-        "description": "Reboot time per connector (HH:MM, droplet local time). Replaces two literals in main.tf.",
+        "description": "Reboot time per connector (HH:MM, America/New_York, the droplet's local time). Keys a and b. The defaults are the times the live connectors use.",
         "required": false,
-        "default": "{a = \"04:00\", b = \"05:00\"}",
-        "validation": "HH:MM 24-hour; the two differ by at least 30 minutes",
+        "default": {
+          "a": "04:00",
+          "b": "05:00"
+        },
+        "validation": "exactly the keys a and b; each HH:MM in 24-hour time; the two reboot times at least 60 minutes apart, measured around the clock across midnight, which also keeps each connector's weekly update (reboot + 30 minutes) at least 30 minutes from the other's reboot",
         "set_where": "tfvars (local plans) or Spacelift stack environment (TF_VAR_*)",
-        "example": "{a = \"04:00\", b = \"05:00\"}",
+        "example": "{ a = \"04:00\", b = \"05:00\" }",
         "sensitivity": "public",
         "sensitive_in_code": false,
-        "status": "planned"
+        "status": "exists"
       },
       {
         "name": "timezone",
@@ -685,6 +686,19 @@
         "sensitive_in_code": false,
         "status": "exists",
         "readers": "same as the calling stack's variable of the same name"
+      },
+      {
+        "name": "resource_key",
+        "type": "string",
+        "description": "Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key.",
+        "required": false,
+        "default": "",
+        "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$",
+        "set_where": "set by the calling stack (not a user setting)",
+        "example": "tor1",
+        "sensitivity": "public",
+        "sensitive_in_code": false,
+        "status": "exists"
       }
     ],
     "modules/firewall": [
@@ -774,6 +788,19 @@
         "sensitivity": "public",
         "sensitive_in_code": false,
         "status": "exists"
+      },
+      {
+        "name": "resource_key",
+        "type": "string",
+        "description": "Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key.",
+        "required": false,
+        "default": "",
+        "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$",
+        "set_where": "set by the calling stack (not a user setting)",
+        "example": "tor1",
+        "sensitivity": "public",
+        "sensitive_in_code": false,
+        "status": "exists"
       }
     ],
     "modules/twingate-bootstrap": [
@@ -841,9 +868,9 @@
       {
         "name": "admin_ssh_public_key",
         "type": "string",
-        "description": "Public key (type and key, no comment) for the cah-admin user.",
+        "description": "Public key for the cah-admin user; an optional trailing comment is dropped before cloud-init.",
         "required": true,
-        "validation": "^ssh-(ed25519|rsa) [A-Za-z0-9+/=]+$ (no comment field)",
+        "validation": "^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)) [A-Za-z0-9+/]+=*( [A-Za-z0-9@._+:=/-]{1,64})?$",
         "set_where": "set by the calling stack (not a user setting)",
         "example": "ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY",
         "sensitivity": "private",
@@ -862,6 +889,19 @@
         "sensitivity": "public",
         "sensitive_in_code": false,
         "status": "exists"
+      },
+      {
+        "name": "resource_key",
+        "type": "string",
+        "description": "Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key.",
+        "required": false,
+        "default": "",
+        "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$",
+        "set_where": "set by the calling stack (not a user setting)",
+        "example": "tor1",
+        "sensitivity": "public",
+        "sensitive_in_code": false,
+        "status": "exists"
       }
     ],
     "modules/twingate-connector": [
@@ -998,6 +1038,19 @@
         "sensitivity": "public",
         "sensitive_in_code": false,
         "status": "exists"
+      },
+      {
+        "name": "resource_key",
+        "type": "string",
+        "description": "Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key.",
+        "required": false,
+        "default": "",
+        "validation": "empty, or ^[a-z][a-z0-9-]{1,23}$",
+        "set_where": "set by the calling stack (not a user setting)",
+        "example": "tor1",
+        "sensitivity": "public",
+        "sensitive_in_code": false,
+        "status": "exists"
       }
     ],
     "modules/aws/vpc": [
@@ -1586,32 +1639,6 @@
     }
   ],
   "hardcoded": [
-    {
-      "name": "reboot time, connector a",
-      "file": "stacks/10-access/main.tf",
-      "literal": "reboot_time = \"04:00\"",
-      "current": "04:00",
-      "stack": "stacks/10-access",
-      "validation": "the bootstrap module checks HH:MM",
-      "set_where": "hard-coded in stacks/10-access/main.tf",
-      "example": "04:00",
-      "sensitivity": "public",
-      "converted_by": "reboot_times (step 2)",
-      "status": "exists"
-    },
-    {
-      "name": "reboot time, connector b",
-      "file": "stacks/10-access/main.tf",
-      "literal": "reboot_time = \"05:00\"",
-      "current": "05:00",
-      "stack": "stacks/10-access",
-      "validation": "the bootstrap module checks HH:MM",
-      "set_where": "hard-coded in stacks/10-access/main.tf",
-      "example": "05:00",
-      "sensitivity": "public",
-      "converted_by": "reboot_times (step 2)",
-      "status": "exists"
-    },
     {
       "name": "droplet timezone",
       "file": "modules/twingate-bootstrap/cloud-init.yaml.tftpl",

+ 1 - 1
docs/wiki/Droplet-Hardening.md

@@ -45,7 +45,7 @@ flowchart TD
 | `disable_root: true` and `PermitRootLogin no` | Root is reached through `sudo`, which is logged. |
 | Passwordless sudo for `cah-admin` | There is no password to type. The gate is the SSH key plus Twingate access. |
 
-The SSH key comment is stripped before it is stored in Doppler (keep only `<type> <key>`), because comments usually hold a username and machine name, and the key ends up in cloud-init and in state.
+The SSH key comment is stripped before it is stored in Doppler (keep only `<type> <key>`), because comments usually hold a username and machine name, and the key ends up in cloud-init and in state. If a key does arrive with one comment word, the module accepts it and drops the comment before rendering cloud-init, but the value in Doppler and the plan still holds it, so stripping it first stays the advice.
 
 ### sshd drop-in (`/etc/ssh/sshd_config.d/99-cah-hardening.conf`)
 

+ 1 - 0
docs/wiki/Reading-Order.md

@@ -60,6 +60,7 @@ Pick the row that sounds like you. Every path is a numbered list: read in that o
 | 2 | [Labs: break it on purpose](Labs-Break-It-on-Purpose.md) | 15 min | Each of the five labs: you predicted the check that would object, and it did. |
 | 3 | [Build it: zero accounts to stage 1](Build-It-From-Zero-Accounts-to-Stage-1.md) | 15 min | Stage 0 applied, stage 1 connected, then torn down and the bill proved zero. |
 | 4 | [Settings reference](Settings-Reference.md) | lookup | You can find where any value lives (variable, tfvars, Doppler or cost.json). |
+| 5 | [Variables, tfvars and secrets](Variables-Tfvars-and-Secrets.md) | 20 min | You can say, for any value, whether it belongs in a variable, a tfvars file, Spacelift, Doppler or cost.json, and why `resource_key` never changes on a live stack. |
 
 The settings reference is a lookup page: it is generated from one manifest and meant to be searched, not read through. Doing, not just reading: Labs adds about 75 minutes (five labs at about 15 minutes each, as the page says).
 

+ 15 - 13
docs/wiki/Settings-Reference.md

@@ -31,30 +31,30 @@ Stack variables are the settings you set per site. Module variables are filled i
 
 | Setting | Type | Default | Validation | Set where | Example | Sensitivity | Status |
 |---|---|---|---|---|---|---|---|
-| `region`<br>DigitalOcean region slug. Planned change: Regex validation for the region slug; the description should say to check the account's available sizes first. | `string` | `"tor1"` | none today (planned: pattern check) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `tor1` | public | exists |
-| `vpc_ip_range`<br>Private CIDR. Must not overlap any homelab range (confirmed in the stage 0 guide before apply). Planned change: Prefix length between /16 and /28, and no overlap with reserved_ranges. | `string` | `"10.78.0.0/24"` | none in the stack; modules/vpc checks it is a private IPv4 CIDR (10/8, 172.16/12, 192.168/16) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `10.99.0.0/24` | private (not a credential, but identifies the owner) | exists |
+| `region`<br>DigitalOcean region slug. Names are built from resource_key, which defaults to this. Check the sizes your account may use in the region (GET /v2/sizes) before changing it. | `string` | `"tor1"` | ^[a-z]{3}[0-9]\$ (three lowercase letters and a digit); the pattern cannot know which sizes the account may use | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `tor1` | public | exists |
+| `vpc_ip_range`<br>Private CIDR for the VPC. Must be the network address and must not overlap any range in reserved_ranges. | `string` | `"10.78.0.0/24"` | private IPv4 CIDR (10/8, 172.16/12, 192.168/16, also checked in modules/vpc); the network address (10.78.0.0/24, not 10.78.0.5/24); prefix length between /16 and /28; no overlap with reserved_ranges (a precondition on the project, because OpenTofu 1.8 cannot compare two variables in a validation) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `10.99.0.0/24` | private (not a credential, but identifies the owner) | exists |
 | `project_name`<br>Name of the DigitalOcean project that groups the resources (the code has no description for it). | `string` | `"clouds-against-humanity"` | none today (DigitalOcean's allowed character set is UNVERIFIED) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `clouds-against-humanity` | public | exists |
-| `reserved_ranges`<br>Ranges you connect to (home networks); vpc_ip_range must not overlap them. | `list(string)` | `[]` | each entry a valid CIDR; vpc_ip_range must not overlap any entry | Doppler or private tfvars (identifies the owner's network) | `["10.50.0.0/16", "10.60.0.0/16"]` | private (not a credential, but identifies the owner) | planned |
-| `resource_key`<br>Key used in resource names instead of region; empty means region. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$; immutable on a live stack | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `tor1` | public | planned |
-| `site_name`<br>Telemetry label for the site; empty means site-&lt;region&gt;. In no resource name or tag. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$; unique across sites | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `site-tor1` | public | planned |
+| `reserved_ranges`<br>Private CIDRs the VPC range must not overlap (your homelab, other VPCs). Optional; they identify your network, so they are never committed. Prompts the human check, does not replace it. | `list(string)` | `[]` | each entry an IPv4 CIDR; vpc_ip_range must not overlap any entry (compared by first and last address) | Spacelift stack environment (TF_VAR_reserved_ranges, a JSON list) or a private tfvars today; Doppler only once a hook line in .spacelift/config.yml requests it (the foundation hooks request only DIGITALOCEAN_TOKEN) | `["10.50.0.0/16", "10.60.0.0/16"]` | private (not a credential, but identifies the owner) | exists |
+| `resource_key`<br>Key used in the names and tags of cloud and Twingate objects instead of region; empty means region, so every name is identical to a stack that never set it. IMMUTABLE for the life of a stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$; immutable on a live stack | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `tor1` | public | exists |
+| `site_name`<br>Telemetry label for the site (metrics and log labels in a later stage); empty means site-&lt;region&gt;. In no resource name, tag or output; changing it replaces nothing. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$; unique across sites (a rule for the person, one stack cannot test it) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `site-tor1` | public | exists |
 | `provider_name`<br>Label for the cloud provider; does not select modules. | `string` | `"digitalocean"` | one of the implemented providers | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `digitalocean` | public | planned |
 
 ### stacks/10-access
 
 | Setting | Type | Default | Validation | Set where | Example | Sensitivity | Status |
 |---|---|---|---|---|---|---|---|
-| `region`<br>DigitalOcean region slug, the same value as stack 00 (the code has no description for it). | `string` | required | none today | Spacelift stack dependency, mapped to a TF_VAR_* environment variable (output of stack 00) | `tor1` | public | exists |
+| `region`<br>DigitalOcean region slug, from the foundation stack's region output. Names are built from resource_key, which defaults to this. | `string` | required | ^[a-z]{3}[0-9]\$ (three lowercase letters and a digit) | Spacelift stack dependency, mapped to a TF_VAR_* environment variable (output of stack 00) | `tor1` | public | exists |
 | `vpc_id`<br>ID of the VPC created by stack 00 (the code has no description for it). | `string` | required | none today (planned: non-empty) | Spacelift stack dependency, mapped to a TF_VAR_* environment variable (output of stack 00) | `00000000-0000-4000-8000-000000000000` | public | exists |
 | `project_id`<br>ID of the DigitalOcean project created by stack 00 (the code has no description for it). | `string` | required | none today (planned: non-empty) | Spacelift stack dependency, mapped to a TF_VAR_* environment variable (output of stack 00) | `00000000-0000-4000-8000-000000000001` | public | exists |
 | `baseline_tag`<br>Baseline firewall tag created by stack 00; the connectors carry it. | `string` | required | starts with "cah-baseline-" | Spacelift stack dependency, mapped to a TF_VAR_* environment variable (output of stack 00) | `cah-baseline-tor1` | public | exists |
 | `twingate_network`<br>Bare Twingate network subdomain (the tenant name). | `string` | required | ^[a-z0-9-]+\$ (no URL, no quotes) | Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (TWINGATE_NETWORK) | `example-tenant` | private (not a credential, but identifies the owner) | exists |
-| `admin_ssh_public_key`<br>Public SSH key for the cah-admin user on the connectors (the stack has no description; modules/twingate-bootstrap requires type and key with no comment). | `string` | required | none in the stack (the bootstrap module requires '&lt;ssh-ed25519\|ssh-rsa&gt; &lt;key&gt;' with no comment); planned: accept a trailing comment | Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (ADMIN_SSH_PUBLIC_KEY) | `ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY` | private (not a credential, but identifies the owner) | exists |
+| `admin_ssh_public_key`<br>Public SSH key for the cah-admin user on the connectors: '&lt;algorithm&gt; &lt;key&gt;' with an optional trailing comment of one word. The comment is dropped before cloud-init, so user_data does not depend on it. | `string` | required | ^(ssh-ed25519\|ssh-rsa\|ecdsa-sha2-nistp(256\|384\|521)) [A-Za-z0-9+/]+=*( [A-Za-z0-9@._+:=/-]{1,64})?\$ (one optional comment word of safe characters; no line break or other whitespace); the same check in modules/twingate-bootstrap | Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (ADMIN_SSH_PUBLIC_KEY) | `ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY` | private (not a credential, but identifies the owner) | exists |
 | `admin_ssh_key_name`<br>Name of an SSH key already registered on the DigitalOcean account. | `string` | required | non-empty | Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (ADMIN_SSH_KEY_NAME) | `example-admin-key` | private (not a credential, but identifies the owner) | exists |
 | `admin_user_ids`<br>Twingate user ids placed in the admin group. | `list(string)` | required | at least one entry | Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (ADMIN_USER_IDS, a JSON list) | `["example-user-id"]` | private (not a credential, but identifies the owner) | exists |
-| `resource_key`<br>Key used in resource names instead of region; empty means region. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$; immutable on a live stack | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `tor1` | public | planned |
-| `site_name`<br>Telemetry label for the site; empty means site-&lt;region&gt;. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$ | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `site-tor1` | public | planned |
+| `resource_key`<br>Key used in the names and tags of cloud and Twingate objects instead of region; empty means region, so every name is identical to a stack that never set it. IMMUTABLE for the life of a stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$; immutable on a live stack | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `tor1` | public | exists |
+| `site_name`<br>Telemetry label for the site (metrics and log labels in a later stage); empty means site-&lt;region&gt;. In no resource name, tag or output; changing it replaces nothing. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$ | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `site-tor1` | public | exists |
 | `provider_name`<br>Label for the cloud provider; does not select modules. | `string` | `"digitalocean"` | one of the implemented providers | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `digitalocean` | public | planned |
-| `reboot_times`<br>Reboot time per connector (HH:MM, droplet local time). Replaces two literals in main.tf. | `map(string)` | `{a = "04:00", b = "05:00"}` | HH:MM 24-hour; the two differ by at least 30 minutes | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `{a = "04:00", b = "05:00"}` | public | planned |
+| `reboot_times`<br>Reboot time per connector (HH:MM, America/New_York, the droplet's local time). Keys a and b. The defaults are the times the live connectors use. | `map(string)` | `{"a": "04:00", "b": "05:00"}` | exactly the keys a and b; each HH:MM in 24-hour time; the two reboot times at least 60 minutes apart, measured around the clock across midnight, which also keeps each connector's weekly update (reboot + 30 minutes) at least 30 minutes from the other's reboot | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `{ a = "04:00", b = "05:00" }` | public | exists |
 | `timezone`<br>Timezone of the droplets. Replaces a literal in the cloud-init template. | `string` | `"America/New_York"` | name from a fixed allow-list of common zones | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `America/New_York` | public | planned |
 | `metrics_enabled`<br>Install node exporter and expose connector metrics. | `bool` | `false` | none | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `true` | public | planned |
 | `node_exporter_port`<br>Node exporter port. | `number` | `9100` | 1024 to 65535 | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `9100` | public | planned |
@@ -113,6 +113,7 @@ Stack variables are the settings you set per site. Module variables are filled i
 | `layer`<br>Stack layer, used in names (for example foundation). | `string` | required | none | set by the calling stack (not a user setting) | `foundation` | public | exists |
 | `region`<br>DigitalOcean region slug. | `string` | required | none | set by the calling stack (not a user setting) | `tor1` | public | exists |
 | `ip_range`<br>Private IPv4 CIDR for the VPC. | `string` | required | valid CIDR in 10/8, 172.16/12 or 192.168/16 | set by the calling stack (not a user setting) | `10.99.0.0/24` | private (not a credential, but identifies the owner) | exists |
+| `resource_key`<br>Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$ | set by the calling stack (not a user setting) | `tor1` | public | exists |
 
 ### modules/firewall
 
@@ -125,6 +126,7 @@ Stack variables are the settings you set per site. Module variables are filled i
 | `extra_outbound_rules`<br>Outbound rules appended to the defaults. | `list(object({protocol=string,port_range=string}))` | `[]` | none | set by the calling stack (not a user setting) | `[{protocol="tcp", port_range="30000-31000"}]` | public | exists |
 | `inbound_from_tag_rules`<br>Inbound rules that admit only droplets carrying this firewall's own tag. Empty means deny-all inbound. | `list(object({protocol=string,port_range=string}))` | `[]` | protocol tcp or udp and a non-empty port_range | set by the calling stack (not a user setting) | `[{protocol="tcp", port_range="22"}]` | public | exists |
 | `outbound_to_tag_rules`<br>Outbound rules that reach only droplets carrying this firewall's own tag (no addresses). Empty means none. | `list(object({protocol=string,port_range=string}))` | `[]` | protocol tcp or udp and a non-empty port_range | set by the calling stack (not a user setting) | `[{protocol="tcp", port_range="22"}]` | public | exists |
+| `resource_key`<br>Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$ | set by the calling stack (not a user setting) | `tor1` | public | exists |
 
 ### modules/twingate-bootstrap
 
@@ -135,8 +137,9 @@ Stack variables are the settings you set per site. Module variables are filled i
 | `remote_network_id`<br>Twingate remote network (site) shared by every connector of the stack. | `string` | required | none | set by the calling stack (not a user setting) | `example-remote-network-id` | public | exists |
 | `instance`<br>One lowercase letter or digit that tells this connector from its siblings (a, b). | `string` | required | ^[a-z0-9]\$ | set by the calling stack (not a user setting) | `a` | public | exists |
 | `twingate_network`<br>Bare Twingate network subdomain. | `string` | required | ^[a-z0-9-]+\$ | set by the calling stack (not a user setting) | `example-tenant` | private (not a credential, but identifies the owner) | exists |
-| `admin_ssh_public_key`<br>Public key (type and key, no comment) for the cah-admin user. | `string` | required | ^ssh-(ed25519\|rsa) [A-Za-z0-9+/=]+\$ (no comment field) | set by the calling stack (not a user setting) | `ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY` | private (not a credential, but identifies the owner) | exists |
+| `admin_ssh_public_key`<br>Public key for the cah-admin user; an optional trailing comment is dropped before cloud-init. | `string` | required | ^(ssh-ed25519\|ssh-rsa\|ecdsa-sha2-nistp(256\|384\|521)) [A-Za-z0-9+/]+=*( [A-Za-z0-9@._+:=/-]{1,64})?\$ | set by the calling stack (not a user setting) | `ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY` | private (not a credential, but identifies the owner) | exists |
 | `reboot_time`<br>HH:MM (America/New_York, the droplet's local time) when unattended-upgrades may reboot this droplet. | `string` | required | ^([01][0-9]\|2[0-3]):[0-5][0-9]\$ | set by the calling stack (not a user setting) | `04:00` | public | exists |
+| `resource_key`<br>Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$ | set by the calling stack (not a user setting) | `tor1` | public | exists |
 
 ### modules/twingate-connector
 
@@ -153,6 +156,7 @@ Stack variables are the settings you set per site. Module variables are filled i
 | `twingate_network`<br>Bare Twingate network subdomain. | `string` | required | none in this module (the bootstrap module checks it) | set by the calling stack (not a user setting) | `example-tenant` | private (not a credential, but identifies the owner) | exists |
 | `admin_ssh_public_key`<br>Public key for the cah-admin user. | `string` | required | none in this module (the bootstrap module checks it) | set by the calling stack (not a user setting) | `ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY` | private (not a credential, but identifies the owner) | exists |
 | `reboot_time`<br>HH:MM (America/New_York) when unattended-upgrades may reboot. | `string` | required | none in this module (the bootstrap module checks it) | set by the calling stack (not a user setting) | `04:00` | public | exists |
+| `resource_key`<br>Key used in resource names in place of region; empty means region. Set by the calling stack from its resource_key. | `string` | `""` | empty, or ^[a-z][a-z0-9-]{1,23}\$ | set by the calling stack (not a user setting) | `tor1` | public | exists |
 
 ### modules/aws/vpc
 
@@ -216,8 +220,6 @@ These are literals in the code, not variables. They are listed so the table is c
 
 | Setting | Where | Current value | Validation | Plan | Status |
 |---|---|---|---|---|---|
-| reboot time, connector a | `stacks/10-access/main.tf` | `04:00` | the bootstrap module checks HH:MM | reboot_times (step 2) | exists |
-| reboot time, connector b | `stacks/10-access/main.tf` | `05:00` | the bootstrap module checks HH:MM | reboot_times (step 2) | exists |
 | droplet timezone | `modules/twingate-bootstrap/cloud-init.yaml.tftpl` | `America/New_York` | asserted by the module tests | timezone (step 2; changes the rendered template) | exists |
 | connector extra outbound rules | `stacks/10-access/main.tf` | `tcp 30000-31000 and udp 1-65535` | none | kept hard-coded on purpose (low value to expose) | exists |
 | connector SSH rule between connectors | `stacks/10-access/main.tf` | `tcp 22, tag to tag` | firewall module validation | kept hard-coded on purpose | exists |

+ 2 - 2
docs/wiki/Terraform-Reference.md

@@ -174,7 +174,7 @@ One DigitalOcean connector: the droplet that runs it. The Twingate connector, it
 | `ssh_key_fingerprint` | string | required | Fingerprint of the admin SSH key already on the DigitalOcean account. |
 | `instance` | string | required | One letter or digit (`a`, `b`) that tells siblings apart. **Validation (in the bootstrap module):** exactly one lowercase letter or digit. |
 | `twingate_network` | string, **sensitive** | required | The bare network subdomain (`acme` for `acme.twingate.com`). Sensitive because the tenant name identifies the tenant. **Validation:** lowercase letters, digits and hyphens only, so a pasted URL or a quoted value is rejected. |
-| `admin_ssh_public_key` | string | required | The public key written for the `cah-admin` user. **Validation:** `ssh-ed25519` or `ssh-rsa` plus the key, no comment field. |
+| `admin_ssh_public_key` | string | required | The public key written for the `cah-admin` user. **Validation:** `ssh-ed25519`, `ssh-rsa` or `ecdsa-sha2-nistp256/384/521`, then the key, then at most one comment word of safe characters. The comment is dropped before the key reaches cloud-init. |
 | `reboot_time` | string | required | `HH:MM` Eastern, when security updates may reboot the droplet. **Validation:** 24-hour time. Each connector gets a different time so they never reboot together. |
 
 ### Resources
@@ -334,7 +334,7 @@ Both are empty blocks. Credentials come from `DIGITALOCEAN_TOKEN`, `TWINGATE_API
 | `digitalocean_tag.connector` | Tag `cah-connector-<region>`. The connector firewall attaches to this one; it is how connectors are allowed to talk to each other. |
 | `twingate_remote_network.this` | The Twingate site `access-<region>`. Both connectors are redundant members of it. `location = "OTHER"` is a required field that only labels where the network is. |
 | `data.digitalocean_ssh_key.admin` | **Looks up** the admin key by name instead of creating it. DigitalOcean refuses to register the same key twice (HTTP 422), and the key already exists, so the stack reads its fingerprint. |
-| `module.connector_a`, `module.connector_b` | Two calls of the same module with different `instance` and `reboot_time` (04:00 and 05:00 Eastern). Written out twice rather than with `for_each` on purpose: a learner can read each connector without a loop. `depends_on = [module.connector_firewall]` makes the firewall exist *before* the droplet boots, because the install needs those outbound rules. |
+| `module.connector_a`, `module.connector_b` | Two calls of the same module with different `instance` and `reboot_time` (`reboot_times["a"]` and `reboot_times["b"]`, defaulting to 04:00 and 05:00 Eastern; the two must differ). Written out twice rather than with `for_each` on purpose: a learner can read each connector without a loop. `depends_on = [module.connector_firewall]` makes the firewall exist *before* the droplet boots, because the install needs those outbound rules. |
 | `module.connector_firewall` | Calls `modules/firewall` with purpose `connector`. Inbound: TCP 22 from the connector tag. Outbound to tag: TCP 22. Extra outbound: TCP `30000-31000` and all UDP, which Twingate needs for its relay and peer-to-peer paths. Inbound from the internet stays zero. |
 | `digitalocean_project_resources.access` | Puts both droplets in the project (`resources` takes their URNs). |
 | `twingate_group.admins` | The group `cah-<region>-admins`, filled from `admin_user_ids`. Access is granted to a group, never to a single person. |

+ 98 - 0
docs/wiki/Variables-Tfvars-and-Secrets.md

@@ -0,0 +1,98 @@
+# Variables, tfvars and secrets: where does this value belong?
+
+> Before this page: [What is infrastructure as code](What-Is-Infrastructure-as-Code.md) explains plan and apply, and [Doppler and secrets](Doppler-and-Secrets.md) explains how a secret reaches a run. This page is the decision table that sits between them.
+
+The stage 2 settings work started with one question: where does `region` live, and where does the VPC range that must not collide with a homelab live? Every value in this repository has exactly one correct home. Put it in the wrong one and the cost is either a leaked identifier in a public repository or a plan that quietly renames live machines.
+
+## The decision table
+
+Ask the questions in order and stop at the first yes.
+
+| Question | Home | Example here |
+|---|---|---|
+| Is it a credential, or would it let someone act as you? | **Doppler**, delivered as an environment variable for one run. Never a variable default, never a value file. | `DIGITALOCEAN_TOKEN`, `TWINGATE_API_TOKEN` |
+| Does it identify your accounts or your network, without being a credential? | **Doppler** for the Twingate and SSH values (the hook requests them by name), and for `reserved_ranges` only once a hook line requests it; today it arrives as a Spacelift stack environment variable (`TF_VAR_reserved_ranges`, a JSON list) or a private value file. The variable is `sensitive = true` where it carries your network. | `twingate_network`, `admin_user_ids`, `reserved_ranges` |
+| Is it the size or count of a billed machine? | **`cost.json`**, edited together with `approved.json`. The cost gate reads it, so nothing else may. | `connector-a` size |
+| Is it a non-secret setting that differs per site and is safe to read in a plan? | **`terraform.tfvars`** for a local plan, or **`TF_VAR_*` in the Spacelift stack environment** for a run. | `region`, `vpc_ip_range`, `reboot_times`, `resource_key` |
+| Is it the shape of a setting (its name, type, validation, safe default)? | **`variables.tf`**, committed, public. | every `variable` block |
+| Is it a fact of the design that nobody should change per site? | **Hard-coded** in the `.tf` file, and listed in `docs/settings.json` under `hardcoded` so it is visible. | the outbound firewall ports Twingate needs |
+
+The full inventory, generated from one machine-readable file, is the [Settings reference](Settings-Reference.md).
+
+## Why tfvars never holds a secret
+
+A value file is a file. It is copied to laptops, pasted into chats, and sits in shell history after a `-var-file` command. It has no read control and no audit trail. Plan files and state repeat every variable that reaches a resource, so a secret that enters through a variable ends up in state as well. A secrets manager gives you the two things a file cannot: who can read it, and a record of who did.
+
+So the repository's `.gitignore` ignores `*.tfvars`, `*.auto.tfvars`, `*.tfvars.json`, `*.auto.tfvars.json` and `*.tfplan`. That rule is a backstop against a mistake, not the protection. The protection is that secrets are never in a value file to begin with.
+
+## Why `*.tfvars` is ignored and `*.example` is committed
+
+`terraform.tfvars.example` does not end in `.tfvars`, so the ignore rule does not match it, and OpenTofu never loads it by itself (it loads only `terraform.tfvars` and `*.auto.tfvars`). That is the point: the example is documentation. It lists every variable of the stack with a comment, using placeholders and documentation ranges (`192.0.2.0/24` and friends) or obviously private ranges. Three tests keep it honest:
+
+- every variable of the stack must have an entry, and nothing may be listed that is not a variable;
+- the example is planned with mocked providers by a generated test, so every validation runs against it;
+- nothing in it may look like a token, an account id, a public address or a real host name.
+
+To use it, copy it to `terraform.tfvars` (git ignores the copy) and change the values. In a private copy of the repository you may choose to commit your own `*.auto.tfvars`; the [capstone](Fork-Private-Stacks-and-the-Pipeline.md) explains that pattern.
+
+## What the new settings do
+
+| Setting | What it is | Rule |
+|---|---|---|
+| `region` | The cloud region, passed to the provider. | Must look like a DigitalOcean slug (`tor1`). |
+| `vpc_ip_range` | The VPC's private range. | A private network address with a prefix between /16 and /28. |
+| `reserved_ranges` | Ranges the VPC must not overlap (your homelab). Optional. | The plan fails if the VPC range overlaps any entry. It only knows what you list. |
+| `reboot_times` | When each connector may reboot: `{ a = "04:00", b = "05:00" }`. | `HH:MM`, at least 60 minutes apart around the clock (so 23:30 and 00:30 pass, 04:00 and 04:59 fail), which keeps each connector's weekly update, 30 minutes after its reboot, clear of the other's reboot. |
+| `admin_ssh_public_key` | The key for the admin user. | A normal key with one trailing comment is accepted. The comment is removed before it reaches the machine. |
+| `resource_key` | The word used in **names and tags** (`access-tor1`). Empty means the region. | Immutable on a live stack. |
+| `site_name` | A **telemetry label** for a later stage. Empty means `site-<region>`. | Appears in no name, tag or output. |
+
+### `resource_key` and `site_name`: one is immutable, and why
+
+Every name here is built from the region today: the Twingate network `access-tor1`, the tag `cah-connector-tor1`, the droplet `access-tor1-connector-a`. If a friendlier label such as `site-tor1` replaced the region in those names, the next plan would rename a Twingate network, a group and two tags, and several of those force a new machine. The connectors would be rebuilt and access would drop.
+
+So there are two settings and they never mix. `resource_key` goes into names and defaults to the region, so with the defaults every name is byte-identical to what is deployed. It cannot be changed on a live stack, because changed names cause widespread plan changes and can replace resources, through the name itself, through tags, or through user_data. `site_name` only labels telemetry. You can change it freely, because nothing in the cloud is named after it. A test reads every `.tf` file and fails if `site_name` appears in anything but its declaration.
+
+## How to run a second site with a new tfvars (conceptually)
+
+Second sites are **not built**. This is how the design says it would go, so you can see why the settings above exist. The [stage 2 design](https://github.com/ChiefGyk3D/Clouds-Against-Humanity/blob/main/docs/superpowers/specs/2026-10-16-stage2-settings-and-mini-soc-design.md) (section 3.3) has the full version.
+
+1. Write a new set of values: a different `region` or a new `resource_key` (for example `tor1-b`), a `vpc_ip_range` that does not overlap the first site (list the first site's range in `reserved_ranges`), and a `site_name`.
+2. Create separate stacks for the new site, each with its own state, environment and Doppler config. A new stack starts from nothing, so its names can use the new key.
+3. The cost gate has to see the second site's machines. The rules for that (an instance manifest per site) are written down in section 3.3 of the design, and [how the gate works](https://github.com/ChiefGyk3D/Clouds-Against-Humanity/blob/main/docs/cost.md) explains why it counts connector module blocks per stack directory today.
+4. A second site costs money, so it needs its own cost approval first.
+
+Never edit the live stack's `resource_key` to "become" the second site.
+
+## The no-op plan check
+
+A change to the settings layer edits code that two live stacks run. The acceptance test is a plan that changes nothing. `scripts/plan_noop_check.py` reads the JSON of a saved plan (`tofu plan -out=plan.tfplan`, then `tofu show -json plan.tfplan`) and a golden list of every resource address in `docs/golden-addresses/`. It fails on any action other than `no-op` (an `update` counts), on an address missing from either side, and on any identity attribute that differs: names, tags, region, size, image. It never prints an attribute value, because `user_data` holds connector tokens.
+
+CI cannot run a real plan, because a real plan needs the live state and credentials. CI proves the checker against mocked plan JSON: a no-op plan passes, and a plan that renames `access-tor1` to `access-site-tor1` fails. **The real gate is the plan you read in Spacelift before you confirm.** The tracked run shows the plan; if it lists anything but "no changes" for these stacks, discard it.
+
+## Exercises
+
+Try each answer before you read it.
+
+1. You want to change the reboot hour of connector b. Which file, and what happens to the machine?
+2. Your homelab uses `10.78.0.0/16` and you set `vpc_ip_range = "10.78.4.0/24"`. What happens, and where?
+3. A friend gives you their public key as `ssh-ed25519 AAAA... alice@laptop`. Does it go through, and what does the machine receive?
+4. You set `site_name = "site-tor1"` on the live stack. What does the plan show?
+5. You set `resource_key = "tor1-main"` on the live access stack. What does the plan show, and what do you do?
+6. Which of these may go in `terraform.tfvars`: the Twingate API token, the VPC range, the SSH key name?
+7. You want a bigger droplet. Where does the size live?
+
+<details>
+<summary>Reference answers</summary>
+
+1. `reboot_times` in a value file or the Spacelift environment (or its default in `variables.tf` for everyone). Two things follow: the two times must stay at least 60 minutes apart, and the change alters the cloud-init text, so the droplet is replaced. That is a deliberate rebuild, not a no-op.
+2. The plan fails before anything is created. `reserved_ranges` must contain `10.78.0.0/16`, and then the overlap check on the foundation project stops the plan with a message. If you forgot to list the range, nothing stops you, because the check only knows what you list.
+3. It goes through; the comment is allowed. The machine receives `ssh-ed25519 AAAA...` with no comment, so the rendered cloud-init is the same as for the bare key.
+4. Nothing. No resource, tag or output uses it, so the plan is a no-op.
+5. Replacements: the Twingate network, group, resources, tag, firewall and both droplets are renamed, and several force a new machine. Discard the run and put the value back. The key is only for a brand new stack.
+6. The VPC range (private, non-secret). The SSH key name is account-specific and comes from Doppler in this repository; the API token is a credential and belongs only in Doppler.
+7. `cost.json`, edited together with `docs/stages/approved.json`. The cost gate checks the price, so the size is not a variable.
+
+</details>
+
+Related: [Settings reference](Settings-Reference.md), [Doppler and secrets](Doppler-and-Secrets.md), [OpenTofu, stacks and modules](OpenTofu-Stacks-and-Modules.md), [CI, tests and the cost gate](CI-Tests-and-Cost-Gate.md).

+ 1 - 0
docs/wiki/_Sidebar.md

@@ -34,6 +34,7 @@
 - [Labs: break it on purpose](Labs-Break-It-on-Purpose.md)
 - [Build it: zero accounts to stage 1](Build-It-From-Zero-Accounts-to-Stage-1.md)
 - [Settings reference](Settings-Reference.md)
+- [Variables, tfvars and secrets](Variables-Tfvars-and-Secrets.md)
 
 </details>
 

+ 4 - 1
modules/firewall/main.tf

@@ -7,6 +7,9 @@ locals {
     { protocol = "udp", port_range = "123" },
   ]
   outbound = concat(local.default_outbound, var.extra_outbound_rules)
+
+  # Names use resource_key when it is set and region otherwise.
+  name_key = var.resource_key != "" ? var.resource_key : var.region
 }
 
 # Inbound is deny-all: DigitalOcean denies all inbound traffic that no rule
@@ -27,7 +30,7 @@ locals {
 # addresses, so there is no address list to pin.
 #trivy:ignore:AVD-DIG-0003
 resource "digitalocean_firewall" "this" {
-  name = "${var.layer}-${var.region}-${var.purpose}"
+  name = "${var.layer}-${local.name_key}-${var.purpose}"
   tags = [var.tag]
 
   dynamic "inbound_rule" {

+ 34 - 0
modules/firewall/tests/firewall.tftest.hcl

@@ -221,3 +221,37 @@ run "contract_members_are_empty_without_member_rules" {
     error_message = "A firewall with only address-based rules has no members."
   }
 }
+
+run "resource_key_changes_the_name_not_the_tag" {
+  command = plan
+  variables {
+    resource_key = "tor1-b"
+  }
+  assert {
+    condition     = digitalocean_firewall.this.name == "foundation-tor1-b-baseline"
+    error_message = "A resource_key must replace the region in the firewall name."
+  }
+  assert {
+    condition     = contains(digitalocean_firewall.this.tags, "cah-baseline-tor1")
+    error_message = "The tag is the caller's; resource_key must not touch it."
+  }
+}
+
+run "an_empty_resource_key_means_the_region_in_the_firewall_name" {
+  command = plan
+  variables {
+    resource_key = ""
+  }
+  assert {
+    condition     = digitalocean_firewall.this.name == "foundation-tor1-baseline"
+    error_message = "An empty resource_key must leave the name as before."
+  }
+}
+
+run "rejects_a_bad_resource_key" {
+  command = plan
+  variables {
+    resource_key = "x"
+  }
+  expect_failures = [var.resource_key]
+}

+ 11 - 0
modules/firewall/variables.tf

@@ -52,3 +52,14 @@ variable "outbound_to_tag_rules" {
     error_message = "Each outbound-to-tag rule needs protocol tcp or udp and a non-empty port_range."
   }
 }
+
+variable "resource_key" {
+  type        = string
+  default     = ""
+  description = "Key used in resource NAMES in place of region. Empty means region, so every name is the same as before this setting existed. Immutable on a live stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name."
+
+  validation {
+    condition     = var.resource_key == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.resource_key))
+    error_message = "resource_key must be empty (meaning region) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}

+ 10 - 1
modules/twingate-bootstrap/main.tf

@@ -5,7 +5,7 @@
 
 resource "twingate_connector" "this" {
   remote_network_id = var.remote_network_id
-  name              = "${var.layer}-${var.region}-connector-${var.instance}"
+  name              = "${var.layer}-${local.name_key}-connector-${var.instance}"
 }
 
 resource "twingate_connector_tokens" "this" {
@@ -13,6 +13,15 @@ resource "twingate_connector_tokens" "this" {
 }
 
 locals {
+  # Names use resource_key when it is set and region otherwise.
+  name_key = var.resource_key != "" ? var.resource_key : var.region
+
+  # What the cloud-init gets for the admin key: "<algorithm> <key>" only. A
+  # trailing comment is accepted by the variable's validation and dropped here,
+  # so user_data is the same whether or not the key carries one.
+  admin_key_parts = split(" ", var.admin_ssh_public_key)
+  admin_key       = "${local.admin_key_parts[0]} ${local.admin_key_parts[1]}"
+
   # The weekly connector update runs half an hour after the nightly reboot
   # window opens, so each connector updates only while its sibling is idle.
   reboot_hour   = tonumber(substr(var.reboot_time, 0, 2))

+ 2 - 2
modules/twingate-bootstrap/outputs.tf

@@ -1,5 +1,5 @@
 output "name" {
-  description = "Name shared by the Twingate connector and the machine: <layer>-<region>-connector-<instance>."
+  description = "Name shared by the Twingate connector and the machine: <layer>-<resource_key or region>-connector-<instance>."
   value       = twingate_connector.this.name
 }
 
@@ -14,7 +14,7 @@ output "user_data" {
     refresh_token = twingate_connector_tokens.this.refresh_token
     network       = var.twingate_network
 
-    admin_ssh_public_key = var.admin_ssh_public_key
+    admin_ssh_public_key = local.admin_key
     reboot_time          = var.reboot_time
     update_hour          = local.update_hour
     update_minute        = local.update_minute

+ 294 - 2
modules/twingate-bootstrap/tests/bootstrap.tftest.hcl

@@ -230,10 +230,230 @@ run "reboot_time_rejects_a_missing_zero_pad" {
   expect_failures = [var.reboot_time]
 }
 
-run "admin_key_rejects_a_comment_and_a_newline" {
+# A normal OpenSSH public key carries a trailing comment. It is accepted, and it
+# is dropped before the key reaches cloud-init, so user_data is the same with or
+# without it.
+run "admin_key_accepts_a_comment_and_renders_without_it" {
   command = plan
   variables {
-    admin_ssh_public_key = "ssh-ed25519 AAAA user@host"
+    admin_ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest user@host.example"
+  }
+  assert {
+    condition     = yamldecode(output.user_data).users[0].ssh_authorized_keys == ["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest"]
+    error_message = "The rendered key must be '<algorithm> <key>' with the comment removed."
+  }
+  assert {
+    condition     = !strcontains(output.user_data, "user@host.example")
+    error_message = "The comment must not appear anywhere in user_data."
+  }
+}
+
+# Golden: the rendered cloud-init for the live connectors, with fixed tokens,
+# measured on origin/main before resource_key and the comment-tolerant key
+# existed. A change here rebuilds the droplets (user_data is force-new), so it
+# must be a deliberate step, never a side effect.
+run "user_data_is_byte_identical_to_the_live_connector_a" {
+  command = plan
+  override_resource {
+    target = twingate_connector_tokens.this
+    values = {
+      access_token  = "fixed-access-token"
+      refresh_token = "fixed-refresh-token"
+    }
+  }
+  variables {
+    reboot_time = "04:00"
+  }
+  assert {
+    condition     = sha256(output.user_data) == "3689d9b99f43d41e827f92b183a7ad2f57b5356587060de66bbd1084c0056e0e"
+    error_message = "user_data for connector a changed. The golden hash was taken on origin/main; a different value means droplets would be replaced."
+  }
+}
+
+run "user_data_is_byte_identical_to_the_live_connector_b" {
+  command = plan
+  override_resource {
+    target = twingate_connector_tokens.this
+    values = {
+      access_token  = "fixed-access-token"
+      refresh_token = "fixed-refresh-token"
+    }
+  }
+  variables {
+    instance    = "b"
+    reboot_time = "05:00"
+  }
+  assert {
+    condition     = sha256(output.user_data) == "de2de6286f955100f199779f2b8a4d0a194b72f28619965c80f858061742790b"
+    error_message = "user_data for connector b changed. The golden hash was taken on origin/main; a different value means droplets would be replaced."
+  }
+}
+
+run "user_data_with_a_comment_matches_the_golden_hash" {
+  command = plan
+  override_resource {
+    target = twingate_connector_tokens.this
+    values = {
+      access_token  = "fixed-access-token"
+      refresh_token = "fixed-refresh-token"
+    }
+  }
+  variables {
+    reboot_time          = "04:00"
+    admin_ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest laptop-2026"
+  }
+  assert {
+    condition     = sha256(output.user_data) == "3689d9b99f43d41e827f92b183a7ad2f57b5356587060de66bbd1084c0056e0e"
+    error_message = "A key with a comment must render the same user_data as the key without one."
+  }
+}
+
+run "admin_key_accepts_rsa_with_padding_and_ecdsa" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAAtest== me"
+  }
+  assert {
+    condition     = yamldecode(output.user_data).users[0].ssh_authorized_keys == ["ssh-rsa AAAAB3NzaC1yc2EAAAAtest=="]
+    error_message = "An rsa key with padding must be accepted and rendered without its comment."
+  }
+}
+
+run "admin_key_accepts_ecdsa" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ecdsa-sha2-nistp256 AAAAE2VjZHNhtest"
+  }
+  assert {
+    condition     = yamldecode(output.user_data).users[0].ssh_authorized_keys == ["ecdsa-sha2-nistp256 AAAAE2VjZHNhtest"]
+    error_message = "An ecdsa key must be accepted."
+  }
+}
+
+run "admin_key_rejects_a_two_word_comment" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA two words"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_newline_after_the_comment" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA user@host\n  - evil"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_trailing_newline" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA\n"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_tab" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519\tAAAA"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_trailing_space" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA "
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_unsafe_comment_characters" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA user;id"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_quote_in_the_comment" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA us\"er"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_hash_in_the_comment" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA #x"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_dollar_brace_in_the_comment" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA $${x}"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_comment_over_64_characters" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA ${join("", [for i in range(65) : "a"])}"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_an_unknown_algorithm" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-dss AAAA"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_an_option_prefix" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "command=\"id\" ssh-ed25519 AAAA"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_an_empty_key" {
+  command = plan
+  variables {
+    admin_ssh_public_key = ""
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_key_with_no_body" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_non_base64_body" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AA!A"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_leading_space" {
+  command = plan
+  variables {
+    admin_ssh_public_key = " ssh-ed25519 AAAA"
   }
   expect_failures = [var.admin_ssh_public_key]
 }
@@ -387,3 +607,75 @@ run "connector_joins_the_callers_remote_network_and_is_named_by_instance" {
     error_message = "The connector must join the caller's remote network and be named <layer>-<region>-connector-<instance>."
   }
 }
+
+# resource_key: the key in NAMES. Empty means region, so the live names stay.
+
+run "resource_key_defaults_to_the_region_in_the_name" {
+  command = plan
+  assert {
+    condition     = output.name == "access-tor1-connector-a"
+    error_message = "With no resource_key the connector is named <layer>-<region>-connector-<instance>."
+  }
+}
+
+run "resource_key_replaces_region_in_the_name_only" {
+  command = plan
+  variables {
+    resource_key = "tor1-b"
+  }
+  assert {
+    condition     = output.name == "access-tor1-b-connector-a"
+    error_message = "A resource_key must replace the region in the name."
+  }
+}
+
+run "resource_key_rejects_uppercase" {
+  command = plan
+  variables {
+    resource_key = "Tor1"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_a_leading_digit" {
+  command = plan
+  variables {
+    resource_key = "1tor"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_one_character" {
+  command = plan
+  variables {
+    resource_key = "a"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_25_characters" {
+  command = plan
+  variables {
+    resource_key = "abcdefghijklmnopqrstuvwxy"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_accepts_24_characters" {
+  command = plan
+  variables {
+    resource_key = "abcdefghijklmnopqrstuvwx"
+  }
+  assert {
+    condition     = output.name == "access-abcdefghijklmnopqrstuvwx-connector-a"
+    error_message = "A 24 character key is the longest allowed."
+  }
+}
+
+run "resource_key_rejects_an_underscore_and_a_space" {
+  command = plan
+  variables {
+    resource_key = "tor_1"
+  }
+  expect_failures = [var.resource_key]
+}

+ 14 - 3
modules/twingate-bootstrap/variables.tf

@@ -34,11 +34,11 @@ variable "twingate_network" {
 
 variable "admin_ssh_public_key" {
   type        = string
-  description = "Public key (type and key, no comment) for the cah-admin user. Key-only access; no password exists."
+  description = "Public key for the cah-admin user: '<algorithm> <key>' with an optional trailing comment of one word of safe characters. The comment is dropped before the key reaches cloud-init, so the machine sees only '<algorithm> <key>'. Key-only access; no password exists."
 
   validation {
-    condition     = can(regex("^ssh-(ed25519|rsa) [A-Za-z0-9+/=]+$", var.admin_ssh_public_key))
-    error_message = "admin_ssh_public_key must be '<ssh-ed25519|ssh-rsa> <key>' with no comment field."
+    condition     = can(regex("^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)) [A-Za-z0-9+/]+=*( [A-Za-z0-9@._+:=/-]{1,64})?$", var.admin_ssh_public_key))
+    error_message = "admin_ssh_public_key must be '<ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|384|521> <base64 key>' with at most one trailing comment word of letters, digits and @ . _ + : = / - (no spaces or line breaks)."
   }
 }
 
@@ -51,3 +51,14 @@ variable "reboot_time" {
     error_message = "reboot_time must be HH:MM in 24-hour time, for example 04:00."
   }
 }
+
+variable "resource_key" {
+  type        = string
+  default     = ""
+  description = "Key used in resource NAMES in place of region. Empty means region, so every name is the same as before this setting existed. Immutable on a live stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name."
+
+  validation {
+    condition     = var.resource_key == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.resource_key))
+    error_message = "resource_key must be empty (meaning region) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}

+ 1 - 0
modules/twingate-connector/main.tf

@@ -5,6 +5,7 @@ module "bootstrap" {
 
   layer                = var.layer
   region               = var.region
+  resource_key         = var.resource_key
   instance             = var.instance
   remote_network_id    = var.remote_network_id
   twingate_network     = var.twingate_network

+ 37 - 0
modules/twingate-connector/tests/connector.tftest.hcl

@@ -172,3 +172,40 @@ run "the_moved_blocks_keep_the_state_addresses" {
     error_message = "Exactly the two moved blocks are expected."
   }
 }
+
+run "resource_key_names_the_droplet_and_the_connector_but_not_the_region" {
+  command = plan
+  variables {
+    resource_key = "tor1-b"
+  }
+  assert {
+    condition     = digitalocean_droplet.connector.name == "access-tor1-b-connector-a" && module.bootstrap.name == "access-tor1-b-connector-a"
+    error_message = "A resource_key must replace the region in the droplet and Twingate connector names."
+  }
+  assert {
+    condition     = digitalocean_droplet.connector.region == "tor1"
+    error_message = "The droplet must still be created in the real region."
+  }
+}
+
+run "an_empty_resource_key_keeps_the_live_name" {
+  command = plan
+  variables {
+    resource_key = ""
+  }
+  assert {
+    condition     = digitalocean_droplet.connector.name == "access-tor1-connector-a"
+    error_message = "An empty resource_key must leave the live droplet name."
+  }
+}
+
+run "a_commented_admin_key_is_accepted_through_the_connector_module" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest user@host"
+  }
+  assert {
+    condition     = digitalocean_droplet.connector.name == "access-tor1-connector-a"
+    error_message = "A key with a comment must plan."
+  }
+}

+ 12 - 1
modules/twingate-connector/variables.tf

@@ -43,10 +43,21 @@ variable "twingate_network" {
 
 variable "admin_ssh_public_key" {
   type        = string
-  description = "Public key (type and key, no comment) for the cah-admin user. Key-only access; no password exists."
+  description = "Public key for the cah-admin user (an optional trailing comment is dropped before cloud-init). Key-only access; no password exists."
 }
 
 variable "reboot_time" {
   type        = string
   description = "HH:MM (America/New_York, the droplet's local time) when unattended-upgrades may reboot this droplet. Give each connector a different time so they never reboot together."
 }
+
+variable "resource_key" {
+  type        = string
+  default     = ""
+  description = "Key used in resource NAMES in place of region. Empty means region, so every name is the same as before this setting existed. Immutable on a live stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name."
+
+  validation {
+    condition     = var.resource_key == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.resource_key))
+    error_message = "resource_key must be empty (meaning region) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}

+ 7 - 1
modules/vpc/main.tf

@@ -1,5 +1,11 @@
+locals {
+  # Names use resource_key when it is set and region otherwise; the region
+  # argument below always takes the real region.
+  name_key = var.resource_key != "" ? var.resource_key : var.region
+}
+
 resource "digitalocean_vpc" "this" {
-  name     = "${var.layer}-${var.region}-vpc"
+  name     = "${var.layer}-${local.name_key}-vpc"
   region   = var.region
   ip_range = var.ip_range
 }

+ 35 - 0
modules/vpc/tests/vpc.tftest.hcl

@@ -33,3 +33,38 @@ run "rejects_malformed_range" {
   }
   expect_failures = [var.ip_range]
 }
+
+# resource_key goes into the name; the region argument always takes the region.
+run "resource_key_changes_the_name_not_the_region" {
+  command = plan
+  variables {
+    resource_key = "tor1-b"
+  }
+  assert {
+    condition     = digitalocean_vpc.this.name == "foundation-tor1-b-vpc"
+    error_message = "A resource_key must replace the region in the name."
+  }
+  assert {
+    condition     = digitalocean_vpc.this.region == "tor1"
+    error_message = "The VPC must still be created in the real region."
+  }
+}
+
+run "an_empty_resource_key_means_the_region" {
+  command = plan
+  variables {
+    resource_key = ""
+  }
+  assert {
+    condition     = digitalocean_vpc.this.name == "foundation-tor1-vpc"
+    error_message = "An empty resource_key must leave the name as before."
+  }
+}
+
+run "rejects_a_bad_resource_key" {
+  command = plan
+  variables {
+    resource_key = "Not Valid"
+  }
+  expect_failures = [var.resource_key]
+}

+ 11 - 0
modules/vpc/variables.tf

@@ -16,3 +16,14 @@ variable "ip_range" {
     error_message = "ip_range must be a private IPv4 CIDR (10/8, 172.16/12 or 192.168/16)."
   }
 }
+
+variable "resource_key" {
+  type        = string
+  default     = ""
+  description = "Key used in resource NAMES in place of region. Empty means region, so every name is the same as before this setting existed. Immutable on a live stack: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Never derived from site_name."
+
+  validation {
+    condition     = var.resource_key == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.resource_key))
+    error_message = "resource_key must be empty (meaning region) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}

+ 94 - 0
scripts/gen_example_tests.py

@@ -0,0 +1,94 @@
+"""Generate stacks/<stack>/tests/example.tftest.hcl from terraform.tfvars.example.
+
+The example value file is only worth committing if it is valid. OpenTofu has no
+way to validate a tfvars file without real providers, but a test file's
+`variables { }` block takes the same assignments, so this script wraps the
+example verbatim in a test that plans the stack with mocked providers. Every
+validation then runs against the example, in the same `tofu test` that CI
+already runs for the stack.
+
+Usage (from the repository root):
+  python -I scripts/gen_example_tests.py            write the test files
+  python -I scripts/gen_example_tests.py --check    fail if one is stale
+  python -I scripts/gen_example_tests.py --root DIR use a different root
+
+Exit codes: 0 ok, 1 stale or missing (--check), 2 usage.
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+EXAMPLE = "terraform.tfvars.example"
+TEST = Path("tests") / "example.tftest.hcl"
+
+HEADER = """\
+# GENERATED from terraform.tfvars.example by scripts/gen_example_tests.py. Do not
+# edit by hand: change the example file and run
+# `python -I scripts/gen_example_tests.py`. CI fails when this file is stale.
+# It plans the stack with the example values, so the example stays valid.
+"""
+
+MOCKS = {
+    "stacks/00-foundation": 'mock_provider "digitalocean" {}\n',
+    "stacks/10-access": """\
+mock_provider "digitalocean" {
+  mock_data "digitalocean_ssh_key" {
+    defaults = {
+      fingerprint = "aa:bb:cc:dd:ee:ff"
+    }
+  }
+}
+mock_provider "twingate" {}
+""",
+}
+
+RUN = """\
+
+run "the_example_values_are_valid" {
+  command = plan
+}
+"""
+
+
+def render(stack: str, root: Path) -> str:
+    example = (root / stack / EXAMPLE).read_text(encoding="utf-8")
+    body = example.rstrip("\n")
+    indented = "\n".join(("  " + line) if line.strip() else "" for line in body.splitlines())
+    return f"{HEADER}\n{MOCKS[stack]}\nvariables {{\n{indented}\n}}\n{RUN}"
+
+
+def main(argv: list[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+    parser.add_argument("--check", action="store_true")
+    parser.add_argument("--root", default=str(Path(__file__).resolve().parent.parent))
+    args = parser.parse_args(argv)
+    root = Path(args.root).resolve()
+    status = 0
+    for stack in MOCKS:
+        target = root / stack / TEST
+        try:
+            want = render(stack, root)
+        except OSError as exc:
+            print(f"gen_example_tests: {stack}: cannot read {EXAMPLE} ({exc.strerror})", file=sys.stderr)
+            return 1
+        if args.check:
+            have = target.read_text(encoding="utf-8") if target.is_file() else None
+            if have != want:
+                print(
+                    f"gen_example_tests: {stack}/{TEST} is out of date. "
+                    "Run: python -I scripts/gen_example_tests.py",
+                    file=sys.stderr,
+                )
+                status = 1
+        else:
+            target.parent.mkdir(parents=True, exist_ok=True)
+            target.write_text(want, encoding="utf-8")
+            print(f"gen_example_tests: wrote {stack}/{TEST}")
+    return status
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 112 - 18
scripts/hcl_variables.py

@@ -11,6 +11,10 @@ Understood:
 - Strings with backslash escapes, `#`, `//` and `/* */` comments, and
   multi-line expressions in brackets, braces or parentheses.
 
+- Literal values: strings, numbers, true/false/null, and lists and objects
+  built from them (for defaults, and for the assignments of a tfvars file read
+  by `parse_assignments`). A comment may follow any value.
+
 Refused (HclError): heredocs, `${` or `%{` template sequences inside a string,
 unbalanced brackets, an unknown attribute or block inside a variable, a
 repeated attribute, a duplicate variable name in one directory, a variable
@@ -152,25 +156,115 @@ def _read_expression(text: str, i: int) -> int:
     return i
 
 
+NUMBER_RE = re.compile(r"-?[0-9]+(\.[0-9]+)?")
+KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
+MAX_DEPTH = 8
+
+
+def _parse_value(text: str, i: int, depth: int = 0):
+    """Parse one literal at text[i]; return (value, index after it)."""
+    if depth > MAX_DEPTH:
+        raise HclError("literal is nested too deeply")
+    i = _skip_ws_comments(text, i)
+    if i >= len(text):
+        raise HclError("expected a value")
+    c = text[i]
+    if c == '"':
+        end = _skip_string(text, i)
+        return json.loads(text[i:end]), end
+    if c == "[":
+        out: list = []
+        i += 1
+        while True:
+            i = _skip_ws_comments(text, i)
+            if text.startswith("]", i):
+                return out, i + 1
+            value, i = _parse_value(text, i, depth + 1)
+            out.append(value)
+            i = _skip_ws_comments(text, i)
+            if text.startswith(",", i):
+                i += 1
+            elif not text.startswith("]", i):
+                raise HclError("list items must be separated by commas")
+    if c == "{":
+        obj: dict = {}
+        i += 1
+        while True:
+            i = _skip_ws_comments(text, i)
+            if text.startswith("}", i):
+                return obj, i + 1
+            if text.startswith('"', i):
+                end = _skip_string(text, i)
+                key = json.loads(text[i:end])
+                i = end
+            else:
+                m = KEY_RE.match(text, i)
+                if not m:
+                    raise HclError("object key is not understood")
+                key, i = m.group(0), m.end()
+            i = _skip_ws_comments(text, i, newlines=False)
+            if not (text.startswith("=", i) or text.startswith(":", i)):
+                raise HclError(f"object key {key!r} has no value")
+            if key in obj:
+                raise HclError(f"object key {key!r} is repeated")
+            obj[key], i = _parse_value(text, i + 1, depth + 1)
+            i = _skip_ws_comments(text, i, newlines=False)
+            if text.startswith(",", i):
+                i += 1
+            elif i < len(text) and text[i] == "}":
+                continue
+            elif i < len(text) and text[i] != "\n":
+                raise HclError("object entries are separated by a comma or a new line")
+    for word, value in (("true", True), ("false", False), ("null", None)):
+        if text.startswith(word, i) and not re.match(
+            r"[A-Za-z0-9_.-]", text[i + len(word) : i + len(word) + 1]
+        ):
+            return value, i + len(word)
+    m = NUMBER_RE.match(text, i)
+    if m and not re.match(r"[A-Za-z0-9_.-]", text[m.end() : m.end() + 1]):
+        s = m.group(0)
+        return (float(s) if "." in s else int(s)), m.end()
+    raise HclError(f"not a simple literal: {text[i : i + 30]!r}")
+
+
 def _literal(expr: str):
-    """Evaluate a literal: string, number, bool, null, [] or {}. Else HclError."""
-    expr = expr.strip()
-    if expr.startswith('"'):
-        end = _skip_string(expr, 0)
-        if expr[end:].strip():
-            raise HclError(f"trailing text after string: {expr!r}")
-        return json.loads(expr)
-    if expr in ("true", "false"):
-        return expr == "true"
-    if expr == "null":
-        return None
-    if re.fullmatch(r"-?[0-9]+(\.[0-9]+)?", expr):
-        return float(expr) if "." in expr else int(expr)
-    if re.fullmatch(r"\[\s*\]", expr):
-        return []
-    if re.fullmatch(r"\{\s*\}", expr):
-        return {}
-    raise HclError(f"default is not a simple literal: {expr!r}")
+    """Evaluate a literal expression. Anything else is an HclError."""
+    value, end = _parse_value(expr, 0)
+    if _skip_ws_comments(expr, end) != len(expr):
+        raise HclError(f"trailing text after a value: {expr[end:].strip()[:30]!r}")
+    return value
+
+
+def parse_assignments(text: str, source: str = "<text>") -> dict:
+    """The top-level `name = literal` lines of a tfvars-style file.
+
+    Fails closed: a block, a heredoc, a repeated name, a value that is not a
+    simple literal, or anything else on a top-level line is an HclError.
+    """
+    out: dict = {}
+    i = 0
+    while True:
+        i = _skip_ws_comments(text, i)
+        if i >= len(text):
+            return out
+        m = NAME_RE.match(text, i)
+        if not m:
+            raise HclError(f"{source}: unexpected text at top level")
+        name = m.group(0)
+        i = _skip_ws_comments(text, m.end(), newlines=False)
+        if not text.startswith("=", i) or text.startswith("==", i):
+            raise HclError(f"{source}: {name}: expected '=' (blocks are not understood)")
+        if name in out:
+            raise HclError(f"{source}: {name} is assigned twice")
+        start = _skip_ws_comments(text, i + 1, newlines=False)
+        end = _read_expression(text, start)
+        if not text[start:end].strip():
+            raise HclError(f"{source}: {name}: empty value")
+        try:
+            out[name] = _literal(text[start:end])
+        except HclError as exc:
+            raise HclError(f"{source}: {name}: {exc}") from exc
+        i = end
 
 
 def _normalize_type(expr: str) -> str:

+ 255 - 0
scripts/plan_noop_check.py

@@ -0,0 +1,255 @@
+#!/usr/bin/env python3
+"""Fail unless a saved OpenTofu plan is a no-op over every known resource.
+
+The stage 2 settings work edits code that two live stacks already run. This
+check is the acceptance test for such an edit: with the default values the plan
+must change nothing. It reads the JSON of a saved plan (`tofu plan -out=plan`
+then `tofu show -json plan`) and a golden file that lists every resource
+address the stack has today, and fails when:
+
+- any managed resource change is not exactly ["no-op"] ("update" counts as a
+  failure; so do create, delete, replace and anything else), or a data source
+  has an action other than "no-op" or "read";
+- any output change is not ["no-op"] or has an unknown value;
+- an address in the plan is missing from the golden list, or an address in
+  the golden list is missing from the plan;
+- a force-new attribute differs between before and after, is unknown after
+  apply, is missing, or differs from the literal the golden file pins;
+- a resource was moved (previous_address) and --allow-moves was not given, or
+  was moved from or to an address the golden file does not list under "moves".
+
+It reads files only and never prints an attribute value (user_data holds
+connector tokens). A failure names the address and the attribute.
+
+CI cannot run a real plan: that needs the live state and credentials. CI proves
+this checker against mocked plan JSON (tests/test_plan_noop_check.py). The real
+gate is the tracked-run plan the maintainer reads in Spacelift before
+confirming; this script is for a plan JSON that exists (a local saved plan, or
+one a run exposes).
+
+Golden file format (docs/golden-addresses/<stack>.json):
+  {
+    "stack": "stacks/10-access",
+    "addresses": {
+      "<address>": {"type": "<resource type>", "force_new": {"<attr>": <expected>}}
+    },
+    "data": ["<data source address>"],
+    "moves": {"<previous address>": "<current address>"}
+  }
+  <expected> is a literal that must equal the attribute, or "@unchanged", which
+  only requires before and after to be equal (for ids and sensitive values).
+  A list of strings is compared as a set.
+
+Usage:
+  python -I scripts/plan_noop_check.py --plan plan.json --golden docs/golden-addresses/10-access.json [--allow-moves]
+
+Exit codes: 0 no-op, 1 the plan changes something or disagrees with the
+golden file, 2 an input file is missing or has a shape this script refuses.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+UNCHANGED = "@unchanged"
+MAX_BYTES = 256 * 1024 * 1024
+
+
+class InputError(ValueError):
+    """An input file is unreadable or has a shape this script refuses."""
+
+
+def load_json(path: Path, what: str) -> dict:
+    try:
+        if path.stat().st_size > MAX_BYTES:
+            raise InputError(f"{what}: file is larger than {MAX_BYTES} bytes")
+        data = json.loads(path.read_text(encoding="utf-8"))
+    except OSError as exc:
+        raise InputError(f"{what}: cannot read {path} ({exc.strerror})") from exc
+    except json.JSONDecodeError as exc:
+        raise InputError(f"{what}: {path} is not JSON ({exc.msg})") from exc
+    if not isinstance(data, dict):
+        raise InputError(f"{what}: the top level must be an object")
+    return data
+
+
+def validate_golden(golden: dict) -> None:
+    """Fail closed on a golden file with an unknown shape."""
+    allowed = {"stack", "note", "addresses", "data", "moves"}
+    extra = set(golden) - allowed
+    if extra:
+        raise InputError(f"golden: unknown keys {sorted(extra)}")
+    if not isinstance(golden.get("stack"), str):
+        raise InputError("golden: 'stack' must be a string")
+    addresses = golden.get("addresses")
+    if not isinstance(addresses, dict) or not addresses:
+        raise InputError("golden: 'addresses' must be a non-empty object")
+    for address, spec in addresses.items():
+        if not isinstance(spec, dict) or set(spec) != {"type", "force_new"}:
+            raise InputError(f"golden: {address}: needs exactly 'type' and 'force_new'")
+        if not isinstance(spec["type"], str) or not isinstance(spec["force_new"], dict):
+            raise InputError(f"golden: {address}: bad 'type' or 'force_new'")
+        if not spec["force_new"]:
+            raise InputError(f"golden: {address}: 'force_new' lists no attribute")
+    data = golden.get("data", [])
+    if not isinstance(data, list) or not all(isinstance(a, str) for a in data):
+        raise InputError("golden: 'data' must be a list of addresses")
+    moves = golden.get("moves", {})
+    if not isinstance(moves, dict) or not all(
+        isinstance(k, str) and isinstance(v, str) for k, v in moves.items()
+    ):
+        raise InputError("golden: 'moves' must map addresses to addresses")
+    for new in moves.values():
+        if new not in addresses:
+            raise InputError(f"golden: move target {new} is not a listed address")
+
+
+def validate_plan(plan: dict) -> list[dict]:
+    if plan.get("errored") is True:
+        raise InputError("plan: the plan is marked errored")
+    changes = plan.get("resource_changes")
+    if not isinstance(changes, list):
+        raise InputError("plan: no 'resource_changes' list (not `tofu show -json` of a plan?)")
+    for entry in changes:
+        if not isinstance(entry, dict):
+            raise InputError("plan: a resource change is not an object")
+        change = entry.get("change")
+        if (
+            not isinstance(entry.get("address"), str)
+            or not isinstance(change, dict)
+            or not isinstance(change.get("actions"), list)
+        ):
+            raise InputError("plan: a resource change has no address or actions")
+    return changes
+
+
+def normalize(value):
+    """Order-insensitive form for lists of strings (tags, sets)."""
+    if isinstance(value, list) and all(isinstance(v, str) for v in value):
+        return sorted(value)
+    return value
+
+
+def attribute_problems(address: str, spec: dict, change: dict) -> list[str]:
+    problems: list[str] = []
+    before = change.get("before")
+    after = change.get("after")
+    if not isinstance(before, dict) or not isinstance(after, dict):
+        return [f"{address}: the plan has no before and after values to compare"]
+    unknown = change.get("after_unknown")
+    unknown = unknown if isinstance(unknown, dict) else {}
+    for attr, expected in spec["force_new"].items():
+        if attr not in before or attr not in after:
+            problems.append(f"{address}: force-new attribute {attr} is missing from the plan")
+            continue
+        if unknown.get(attr):
+            problems.append(f"{address}: force-new attribute {attr} is unknown after apply")
+            continue
+        if normalize(before[attr]) != normalize(after[attr]):
+            problems.append(f"{address}: force-new attribute {attr} differs between before and after")
+            continue
+        if expected != UNCHANGED and normalize(expected) != normalize(after[attr]):
+            problems.append(f"{address}: force-new attribute {attr} is not the golden value")
+    return problems
+
+
+def output_problems(plan: dict) -> list[str]:
+    """Any output that would change. Stack 10 reads the foundation outputs."""
+    outputs = plan.get("output_changes", {})
+    if not isinstance(outputs, dict):
+        raise InputError("plan: 'output_changes' is not an object")
+    problems: list[str] = []
+    for name, change in sorted(outputs.items()):
+        if not isinstance(change, dict) or not isinstance(change.get("actions"), list):
+            raise InputError(f"plan: output {name} has no actions")
+        if change["actions"] != ["no-op"]:
+            problems.append(f"output {name}: action is {change['actions']}, expected [\"no-op\"]")
+        if change.get("after_unknown"):
+            problems.append(f"output {name}: value is unknown after apply")
+    return problems
+
+
+def check(plan: dict, golden: dict, allow_moves: bool = False) -> list[str]:
+    """Every reason the plan is not a clean no-op over the golden addresses."""
+    validate_golden(golden)
+    changes = validate_plan(plan)
+    addresses = golden["addresses"]
+    data = set(golden.get("data", []))
+    moves = golden.get("moves", {})
+    problems: list[str] = []
+    seen: set[str] = set()
+
+    for entry in changes:
+        address = entry["address"]
+        change = entry["change"]
+        actions = change["actions"]
+        if address in seen:
+            problems.append(f"{address}: appears twice in the plan")
+            continue
+        seen.add(address)
+
+        previous = entry.get("previous_address")
+        if previous and previous != address:
+            if not allow_moves:
+                problems.append(f"{address}: moved from another address (use --allow-moves for the bootstrap moves)")
+            elif moves.get(previous) != address:
+                problems.append(f"{address}: moved from an address the golden file does not allow")
+
+        if entry.get("mode") == "data":
+            if address not in data:
+                problems.append(f"{address}: data source is not in the golden list")
+            if actions not in (["no-op"], ["read"]):
+                problems.append(f"{address}: data source action is {actions}, expected no-op or read")
+            continue
+
+        if address not in addresses:
+            problems.append(f"{address}: in the plan but not in the golden list")
+            continue
+        if actions != ["no-op"]:
+            problems.append(f"{address}: action is {actions}, expected [\"no-op\"]")
+        spec = addresses[address]
+        resource_type = entry.get("type")
+        if resource_type is not None and resource_type != spec["type"]:
+            problems.append(f"{address}: type is not the golden type")
+        problems.extend(attribute_problems(address, spec, change))
+
+    for address in sorted(set(addresses) - seen):
+        problems.append(f"{address}: in the golden list but missing from the plan")
+    problems.extend(output_problems(plan))
+    # A data source read at plan time may be absent from resource_changes. It is
+    # not a managed resource, so the golden "data" list is not required to appear.
+    return problems
+
+
+def main(argv: list[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+    parser.add_argument("--plan", required=True, help="JSON from `tofu show -json <planfile>`")
+    parser.add_argument("--golden", required=True, help="docs/golden-addresses/<stack>.json")
+    parser.add_argument(
+        "--allow-moves",
+        action="store_true",
+        help="accept the moves listed in the golden file (the bootstrap `moved` blocks)",
+    )
+    args = parser.parse_args(argv)
+    try:
+        golden = load_json(Path(args.golden), "golden")
+        plan = load_json(Path(args.plan), "plan")
+        problems = check(plan, golden, args.allow_moves)
+    except InputError as exc:
+        print(f"plan no-op check ERROR: {exc}", file=sys.stderr)
+        return 2
+    if problems:
+        print("plan no-op check FAILED (attribute values are never printed):")
+        for problem in problems:
+            print(f"  {problem}")
+        return 1
+    count = len(golden["addresses"])
+    print(f"plan no-op check passed: {count} addresses, all no-op, force-new attributes unchanged")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 45 - 10
stacks/00-foundation/main.tf

@@ -1,25 +1,60 @@
+locals {
+  # Names and tags use resource_key when it is set and region otherwise. The
+  # region argument of every resource and of the modules stays var.region.
+  resource_key = var.resource_key != "" ? var.resource_key : var.region
+
+  # First and last address of an IPv4 CIDR as a number, so two ranges can be
+  # compared. OpenTofu has no overlap function. cidrhost(range, -1) is the last
+  # address. Invalid entries are caught by the variables' own validation.
+  vpc_bounds = [
+    for o in [split(".", cidrhost(var.vpc_ip_range, 0)), split(".", cidrhost(var.vpc_ip_range, -1))] :
+    (tonumber(o[0]) * 16777216) + (tonumber(o[1]) * 65536) + (tonumber(o[2]) * 256) + tonumber(o[3])
+  ]
+  reserved_bounds = [
+    for c in var.reserved_ranges : [
+      for o in [split(".", cidrhost(c, 0)), split(".", cidrhost(c, -1))] :
+      (tonumber(o[0]) * 16777216) + (tonumber(o[1]) * 65536) + (tonumber(o[2]) * 256) + tonumber(o[3])
+    ]
+  ]
+  # Two ranges overlap when each starts no later than the other ends.
+  overlaps_reserved = anytrue([
+    for b in local.reserved_bounds : local.vpc_bounds[0] <= b[1] && b[0] <= local.vpc_bounds[1]
+  ])
+}
+
 resource "digitalocean_project" "this" {
   name        = var.project_name
   purpose     = "Service or API"
   environment = "Production"
   description = "Managed by OpenTofu through Spacelift."
+
+  # A precondition, not a variable validation: OpenTofu 1.8 (the pinned minimum)
+  # cannot compare one variable with another in a validation. It changes no plan.
+  lifecycle {
+    precondition {
+      condition     = !local.overlaps_reserved
+      error_message = "vpc_ip_range overlaps a range in reserved_ranges. Pick a range that overlaps none of them."
+    }
+  }
 }
 
 resource "digitalocean_tag" "baseline" {
-  name = "cah-baseline-${var.region}"
+  name = "cah-baseline-${local.resource_key}"
 }
 
 module "vpc" {
-  source   = "../../modules/vpc"
-  layer    = "foundation"
-  region   = var.region
-  ip_range = var.vpc_ip_range
+  source       = "../../modules/vpc"
+  layer        = "foundation"
+  region       = var.region
+  resource_key = var.resource_key
+  ip_range     = var.vpc_ip_range
 }
 
 module "baseline_firewall" {
-  source  = "../../modules/firewall"
-  layer   = "foundation"
-  region  = var.region
-  purpose = "baseline"
-  tag     = digitalocean_tag.baseline.name
+  source       = "../../modules/firewall"
+  layer        = "foundation"
+  region       = var.region
+  resource_key = var.resource_key
+  purpose      = "baseline"
+  tag          = digitalocean_tag.baseline.name
 }

+ 36 - 0
stacks/00-foundation/terraform.tfvars.example

@@ -0,0 +1,36 @@
+# Example values for stacks/00-foundation. Copy this file to terraform.tfvars
+# (which git ignores) for a local plan. Never put a token, key or password in a
+# value file: those live in Doppler. Every value here is a placeholder or a
+# private/documentation range, not a real one. The real values of a live stack
+# come from the Spacelift stack environment (TF_VAR_*) or Doppler.
+#
+# Sizes are not set here. A droplet size lives in cost.json, so the cost gate
+# stays the one place that prices it (see docs/cost.md).
+
+# DigitalOcean region slug: three lowercase letters and a digit. Check the sizes
+# your account may use there first (GET /v2/sizes).
+region = "tor1"
+
+# Private CIDR for the VPC, written as its network address. Prefix length between
+# /16 and /28, and it must not overlap anything in reserved_ranges.
+vpc_ip_range = "10.99.0.0/24"
+
+# Private CIDRs the VPC range must not overlap: your homelab, other VPCs,
+# anything you connect to. These identify your network, so never commit the real
+# list. Today it arrives as TF_VAR_reserved_ranges in the Spacelift stack
+# environment (a JSON list) or from a private tfvars; Doppler only once a hook
+# line in .spacelift/config.yml requests it.
+reserved_ranges = ["10.50.0.0/16", "10.60.0.0/16"]
+
+# Name of the DigitalOcean project that groups the resources.
+project_name = "clouds-against-humanity"
+
+# Used in the NAMES and TAGS of cloud objects. Empty means region, so every name
+# is the same as before this setting existed. IMMUTABLE for the life of a stack:
+# changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Set it only on a NEW stack,
+# for example "tor1-b" for a second site in the same region.
+resource_key = ""
+
+# A label for telemetry only (empty means "site-<region>"). It appears in no
+# resource name, tag or output, and changing it replaces nothing.
+site_name = "site-tor1"

+ 49 - 0
stacks/00-foundation/tests/example.tftest.hcl

@@ -0,0 +1,49 @@
+# GENERATED from terraform.tfvars.example by scripts/gen_example_tests.py. Do not
+# edit by hand: change the example file and run
+# `python -I scripts/gen_example_tests.py`. CI fails when this file is stale.
+# It plans the stack with the example values, so the example stays valid.
+
+mock_provider "digitalocean" {}
+
+variables {
+  # Example values for stacks/00-foundation. Copy this file to terraform.tfvars
+  # (which git ignores) for a local plan. Never put a token, key or password in a
+  # value file: those live in Doppler. Every value here is a placeholder or a
+  # private/documentation range, not a real one. The real values of a live stack
+  # come from the Spacelift stack environment (TF_VAR_*) or Doppler.
+  #
+  # Sizes are not set here. A droplet size lives in cost.json, so the cost gate
+  # stays the one place that prices it (see docs/cost.md).
+
+  # DigitalOcean region slug: three lowercase letters and a digit. Check the sizes
+  # your account may use there first (GET /v2/sizes).
+  region = "tor1"
+
+  # Private CIDR for the VPC, written as its network address. Prefix length between
+  # /16 and /28, and it must not overlap anything in reserved_ranges.
+  vpc_ip_range = "10.99.0.0/24"
+
+  # Private CIDRs the VPC range must not overlap: your homelab, other VPCs,
+  # anything you connect to. These identify your network, so never commit the real
+  # list. Today it arrives as TF_VAR_reserved_ranges in the Spacelift stack
+  # environment (a JSON list) or from a private tfvars; Doppler only once a hook
+  # line in .spacelift/config.yml requests it.
+  reserved_ranges = ["10.50.0.0/16", "10.60.0.0/16"]
+
+  # Name of the DigitalOcean project that groups the resources.
+  project_name = "clouds-against-humanity"
+
+  # Used in the NAMES and TAGS of cloud objects. Empty means region, so every name
+  # is the same as before this setting existed. IMMUTABLE for the life of a stack:
+  # changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. Set it only on a NEW stack,
+  # for example "tor1-b" for a second site in the same region.
+  resource_key = ""
+
+  # A label for telemetry only (empty means "site-<region>"). It appears in no
+  # resource name, tag or output, and changing it replaces nothing.
+  site_name = "site-tor1"
+}
+
+run "the_example_values_are_valid" {
+  command = plan
+}

+ 435 - 0
stacks/00-foundation/tests/foundation.tftest.hcl

@@ -46,3 +46,438 @@ run "baseline_firewall_has_no_tag_scoped_rules_in_either_direction" {
     error_message = "The baseline firewall must not carry any tag-scoped rule; that is the connector firewall's job."
   }
 }
+
+# --- golden names ------------------------------------------------------------
+# These are the names the live stack has today. They are asserted with the
+# defaults, so a change that would rename a live object fails here.
+
+run "golden_names_with_defaults" {
+  command = plan
+  assert {
+    condition     = digitalocean_tag.baseline.name == "cah-baseline-tor1"
+    error_message = "The baseline tag name changed."
+  }
+  assert {
+    condition     = module.vpc.name == "foundation-tor1-vpc"
+    error_message = "The VPC name changed."
+  }
+  assert {
+    condition     = module.baseline_firewall.name == "foundation-tor1-baseline"
+    error_message = "The baseline firewall name changed."
+  }
+  assert {
+    condition     = digitalocean_project.this.name == "clouds-against-humanity"
+    error_message = "The project name changed."
+  }
+  assert {
+    condition     = module.vpc.ip_range == "10.78.0.0/24"
+    error_message = "The VPC range changed."
+  }
+  assert {
+    condition     = output.region == "tor1" && output.baseline_tag == "cah-baseline-tor1"
+    error_message = "The outputs stack 10 reads changed."
+  }
+}
+
+# --- resource_key and site_name ---------------------------------------------
+
+run "an_empty_resource_key_means_the_region" {
+  command = plan
+  variables {
+    resource_key = ""
+  }
+  assert {
+    condition     = digitalocean_tag.baseline.name == "cah-baseline-tor1" && module.vpc.name == "foundation-tor1-vpc" && module.baseline_firewall.name == "foundation-tor1-baseline"
+    error_message = "An empty resource_key must leave every name as it is today."
+  }
+}
+
+run "resource_key_names_everything_and_the_region_stays_the_region" {
+  command = plan
+  variables {
+    resource_key = "tor1-b"
+  }
+  assert {
+    condition     = digitalocean_tag.baseline.name == "cah-baseline-tor1-b" && module.vpc.name == "foundation-tor1-b-vpc" && module.baseline_firewall.name == "foundation-tor1-b-baseline"
+    error_message = "A resource_key must replace the region in the tag, VPC and firewall names."
+  }
+  assert {
+    condition     = output.region == "tor1"
+    error_message = "The region output is the real region, never the key."
+  }
+  assert {
+    condition     = length(regexall("region\\s*=\\s*var.region", file("${path.module}/main.tf"))) == 2
+    error_message = "Both modules must still receive the real region for their region argument."
+  }
+}
+
+run "site_name_changes_no_name" {
+  command = plan
+  variables {
+    site_name = "site-tor1"
+  }
+  assert {
+    condition     = digitalocean_tag.baseline.name == "cah-baseline-tor1" && module.vpc.name == "foundation-tor1-vpc" && module.baseline_firewall.name == "foundation-tor1-baseline"
+    error_message = "site_name is a telemetry label and must change no name."
+  }
+}
+
+run "no_source_file_uses_site_name" {
+  command = plan
+  assert {
+    condition     = !strcontains(file("${path.module}/main.tf"), "site_name") && !strcontains(file("${path.module}/outputs.tf"), "site_name")
+    error_message = "site_name must not appear in main.tf or outputs.tf: it is for telemetry labels only."
+  }
+}
+
+run "resource_key_rejects_uppercase" {
+  command = plan
+  variables {
+    resource_key = "Tor1"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_a_leading_digit" {
+  command = plan
+  variables {
+    resource_key = "1tor"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_one_character" {
+  command = plan
+  variables {
+    resource_key = "a"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_25_characters" {
+  command = plan
+  variables {
+    resource_key = "abcdefghijklmnopqrstuvwxy"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_an_underscore" {
+  command = plan
+  variables {
+    resource_key = "tor_1"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "site_name_rejects_uppercase" {
+  command = plan
+  variables {
+    site_name = "Site-Tor1"
+  }
+  expect_failures = [var.site_name]
+}
+
+run "site_name_rejects_25_characters" {
+  command = plan
+  variables {
+    site_name = "abcdefghijklmnopqrstuvwxy"
+  }
+  expect_failures = [var.site_name]
+}
+
+run "site_name_accepts_the_empty_sentinel_and_a_valid_name" {
+  command = plan
+  variables {
+    site_name = ""
+  }
+  assert {
+    condition     = output.region == "tor1"
+    error_message = "An empty site_name must be accepted."
+  }
+}
+
+# --- region ------------------------------------------------------------------
+
+run "region_accepts_other_digitalocean_slugs" {
+  command = plan
+  variables {
+    region = "sfo3"
+  }
+  assert {
+    condition     = digitalocean_tag.baseline.name == "cah-baseline-sfo3"
+    error_message = "A valid slug must be accepted and flow into the name."
+  }
+}
+
+run "region_rejects_uppercase" {
+  command = plan
+  variables {
+    region = "Tor1"
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_a_city_name" {
+  command = plan
+  variables {
+    region = "toronto"
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_no_digit" {
+  command = plan
+  variables {
+    region = "tor"
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_two_digits" {
+  command = plan
+  variables {
+    region = "tor12"
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_empty" {
+  command = plan
+  variables {
+    region = ""
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_a_newline" {
+  command = plan
+  variables {
+    region = "tor1\n"
+  }
+  expect_failures = [var.region]
+}
+
+# --- vpc_ip_range ------------------------------------------------------------
+
+run "vpc_range_accepts_the_slash_16_and_slash_28_limits" {
+  command = plan
+  variables {
+    vpc_ip_range = "10.99.0.0/16"
+  }
+  assert {
+    condition     = module.vpc.ip_range == "10.99.0.0/16"
+    error_message = "A /16 must be accepted."
+  }
+}
+
+run "vpc_range_accepts_a_slash_28" {
+  command = plan
+  variables {
+    vpc_ip_range = "192.168.4.16/28"
+  }
+  assert {
+    condition     = module.vpc.ip_range == "192.168.4.16/28"
+    error_message = "A /28 network address must be accepted."
+  }
+}
+
+run "vpc_range_rejects_a_public_range" {
+  command = plan
+  variables {
+    vpc_ip_range = "8.8.8.0/24"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_a_documentation_range" {
+  command = plan
+  variables {
+    vpc_ip_range = "192.0.2.0/24"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_a_host_address_not_the_network" {
+  command = plan
+  variables {
+    vpc_ip_range = "10.78.0.5/24"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_a_slash_8" {
+  command = plan
+  variables {
+    vpc_ip_range = "10.0.0.0/8"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_a_slash_15" {
+  command = plan
+  variables {
+    vpc_ip_range = "10.78.0.0/15"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_a_slash_29" {
+  command = plan
+  variables {
+    vpc_ip_range = "10.78.0.0/29"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_a_malformed_range" {
+  command = plan
+  variables {
+    vpc_ip_range = "not-a-cidr"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+run "vpc_range_rejects_ipv6" {
+  command = plan
+  variables {
+    vpc_ip_range = "fd00::/64"
+  }
+  expect_failures = [var.vpc_ip_range]
+}
+
+# --- reserved_ranges (overlap) -----------------------------------------------
+# The VPC range in these runs is the default 10.78.0.0/24.
+
+run "no_reserved_ranges_is_fine" {
+  command = plan
+  variables {
+    reserved_ranges = []
+  }
+  assert {
+    condition     = module.vpc.ip_range == "10.78.0.0/24"
+    error_message = "An empty reserved_ranges list must plan."
+  }
+}
+
+run "a_disjoint_reserved_range_is_fine" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.50.0.0/16", "192.168.0.0/16"]
+  }
+  assert {
+    condition     = module.vpc.ip_range == "10.78.0.0/24"
+    error_message = "Disjoint ranges must plan."
+  }
+}
+
+run "an_adjacent_range_after_is_fine" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.1.0/24"]
+  }
+  assert {
+    condition     = module.vpc.ip_range == "10.78.0.0/24"
+    error_message = "A range that starts right after the VPC range does not overlap it."
+  }
+}
+
+run "an_adjacent_range_before_is_fine" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.77.255.0/24"]
+  }
+  assert {
+    condition     = module.vpc.ip_range == "10.78.0.0/24"
+    error_message = "A range that ends right before the VPC range does not overlap it."
+  }
+}
+
+run "an_equal_range_overlaps" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.0.0/24"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "a_reserved_range_containing_the_vpc_range_overlaps" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.0.0/16"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "a_reserved_range_inside_the_vpc_range_overlaps" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.0.128/25"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "sharing_only_the_last_address_overlaps" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.0.255/32"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "sharing_only_the_first_address_overlaps" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.0.0/32"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "the_overlap_is_found_in_any_entry_not_just_the_first" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.50.0.0/16", "172.16.0.0/12", "10.78.0.64/26"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "overlap_is_checked_against_a_changed_vpc_range" {
+  command = plan
+  variables {
+    vpc_ip_range    = "172.20.0.0/20"
+    reserved_ranges = ["172.16.0.0/12"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "a_non_canonical_reserved_range_is_still_compared_by_its_network" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.78.0.77/24"]
+  }
+  expect_failures = [digitalocean_project.this]
+}
+
+run "a_reserved_range_must_be_a_cidr" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.50.0.0/16", "nonsense"]
+  }
+  expect_failures = [var.reserved_ranges]
+}
+
+run "a_reserved_range_must_not_be_a_bare_address" {
+  command = plan
+  variables {
+    reserved_ranges = ["10.50.0.1"]
+  }
+  expect_failures = [var.reserved_ranges]
+}
+
+run "reserved_ranges_are_sensitive_and_in_no_output" {
+  command = plan
+  assert {
+    condition     = !strcontains(file("${path.module}/outputs.tf"), "reserved_ranges")
+    error_message = "reserved_ranges identify the owner's network and must not be an output."
+  }
+}

+ 59 - 2
stacks/00-foundation/variables.tf

@@ -1,16 +1,73 @@
 variable "region" {
   type        = string
   default     = "tor1"
-  description = "DigitalOcean region slug."
+  description = "DigitalOcean region slug (three lowercase letters and a digit, for example tor1). Names are built from resource_key, which defaults to this value. Check the sizes your account may use in this region (GET /v2/sizes) before changing it."
+
+  validation {
+    condition     = can(regex("^[a-z]{3}[0-9]$", var.region))
+    error_message = "region must be a DigitalOcean region slug: three lowercase letters and a digit, for example tor1."
+  }
 }
 
 variable "vpc_ip_range" {
   type        = string
   default     = "10.78.0.0/24"
-  description = "Private CIDR. Must not overlap any homelab range (confirmed in the stage 0 guide before apply)."
+  description = "Private CIDR. Must not overlap any homelab range: list those in reserved_ranges and the plan fails on an overlap. Must be the network address (10.78.0.0/24, not 10.78.0.5/24)."
+
+  validation {
+    condition     = can(cidrnetmask(var.vpc_ip_range)) && can(regex("^(10\\.|172\\.(1[6-9]|2[0-9]|3[01])\\.|192\\.168\\.)", var.vpc_ip_range))
+    error_message = "vpc_ip_range must be a private IPv4 CIDR (10/8, 172.16/12 or 192.168/16)."
+  }
+
+  validation {
+    condition     = try(cidrsubnet(var.vpc_ip_range, 0, 0) == var.vpc_ip_range, false)
+    error_message = "vpc_ip_range must be written as its network address, for example 10.78.0.0/24 and not 10.78.0.5/24."
+  }
+
+  validation {
+    condition     = try(tonumber(split("/", var.vpc_ip_range)[1]) >= 16 && tonumber(split("/", var.vpc_ip_range)[1]) <= 28, false)
+    error_message = "vpc_ip_range must have a prefix length between /16 and /28."
+  }
+}
+
+variable "reserved_ranges" {
+  type        = list(string)
+  default     = []
+  sensitive   = true
+  description = "Private CIDRs the VPC range must not overlap (your homelab, other VPCs, anything you connect to). Optional. They identify your network, so never commit them. Today they reach a run as the Spacelift stack environment variable TF_VAR_reserved_ranges (a JSON list) or from a private tfvars. Doppler carries them only once a line in .spacelift/config.yml requests them; the foundation hooks request only DIGITALOCEAN_TOKEN. The check only knows the ranges you list; it prompts the human check, it does not replace it."
+
+  validation {
+    condition     = alltrue([for c in var.reserved_ranges : can(cidrnetmask(c))])
+    error_message = "Every reserved_ranges entry must be an IPv4 CIDR such as 10.50.0.0/16."
+  }
 }
 
 variable "project_name" {
   type    = string
   default = "clouds-against-humanity"
 }
+
+variable "resource_key" {
+  type        = string
+  default     = ""
+  description = "Key used in the NAMES and TAGS of cloud objects (cah-baseline-<key>, foundation-<key>-vpc). Empty means region, so every name is identical to a stack that never set it. IMMUTABLE FOR THE LIFE OF A STACK: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. A second site in the same region sets its own key on a NEW stack only. Never derived from site_name."
+
+  validation {
+    condition     = var.resource_key == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.resource_key))
+    error_message = "resource_key must be empty (meaning region) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}
+
+# Declared for the telemetry stage (stack 20) and deliberately used by no resource,
+# name, tag or output until then; wiring it in would show as a plan change.
+# tflint-ignore: terraform_unused_declarations
+variable "site_name" {
+  type        = string
+  default     = ""
+  description = "Telemetry label only (metrics and log labels in a later stage). Empty means site-<region>. Appears in no resource name, tag or output, and changing it replaces nothing. Unique across your sites."
+
+  validation {
+    condition     = var.site_name == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.site_name))
+    error_message = "site_name must be empty (meaning site-<region>) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}

+ 21 - 14
stacks/10-access/main.tf

@@ -1,17 +1,21 @@
 locals {
+  # Names and tags use resource_key when it is set and region otherwise. The
+  # region argument of the droplets and modules stays var.region.
+  resource_key = var.resource_key != "" ? var.resource_key : var.region
+
   cost        = jsondecode(file("${path.module}/cost.json"))
   connector_a = one([for r in local.cost.resources : r if r.name == "connector-a"])
   connector_b = one([for r in local.cost.resources : r if r.name == "connector-b"])
 }
 
 resource "digitalocean_tag" "connector" {
-  name = "cah-connector-${var.region}"
+  name = "cah-connector-${local.resource_key}"
 }
 
 # One site and one SSH key for every connector, so the connectors are redundant
 # members of the same Twingate remote network.
 resource "twingate_remote_network" "this" {
-  name     = "access-${var.region}"
+  name     = "access-${local.resource_key}"
   location = "OTHER"
 }
 
@@ -25,6 +29,7 @@ module "connector_a" {
   source              = "../../modules/twingate-connector"
   layer               = "access"
   region              = var.region
+  resource_key        = var.resource_key
   vpc_id              = var.vpc_id
   tags                = [var.baseline_tag, digitalocean_tag.connector.name]
   size                = local.connector_a.size
@@ -34,8 +39,9 @@ module "connector_a" {
   twingate_network    = var.twingate_network
 
   admin_ssh_public_key = var.admin_ssh_public_key
-  # Eastern time, staggered so the two connectors never reboot together.
-  reboot_time = "04:00"
+  # Eastern time, staggered so the two connectors never reboot together
+  # (reboot_times is validated to hold two different times).
+  reboot_time = var.reboot_times["a"]
 
   # The outbound rules must exist before the droplet boots and starts to install.
   depends_on = [module.connector_firewall]
@@ -45,6 +51,7 @@ module "connector_b" {
   source              = "../../modules/twingate-connector"
   layer               = "access"
   region              = var.region
+  resource_key        = var.resource_key
   vpc_id              = var.vpc_id
   tags                = [var.baseline_tag, digitalocean_tag.connector.name]
   size                = local.connector_b.size
@@ -54,8 +61,7 @@ module "connector_b" {
   twingate_network    = var.twingate_network
 
   admin_ssh_public_key = var.admin_ssh_public_key
-  # Eastern time, staggered so the two connectors never reboot together.
-  reboot_time = "05:00"
+  reboot_time          = var.reboot_times["b"]
 
   depends_on = [module.connector_firewall]
 }
@@ -75,11 +81,12 @@ module "connector_b" {
 # requires outbound UDP to any port for peer-to-peer connections, so UDP is
 # open outbound only; inbound stays deny-all. Record the check date in the stage guide.
 module "connector_firewall" {
-  source  = "../../modules/firewall"
-  layer   = "access"
-  region  = var.region
-  purpose = "connector"
-  tag     = digitalocean_tag.connector.name
+  source       = "../../modules/firewall"
+  layer        = "access"
+  region       = var.region
+  resource_key = var.resource_key
+  purpose      = "connector"
+  tag          = digitalocean_tag.connector.name
   inbound_from_tag_rules = [
     { protocol = "tcp", port_range = "22" },
   ]
@@ -98,12 +105,12 @@ resource "digitalocean_project_resources" "access" {
 }
 
 resource "twingate_group" "admins" {
-  name     = "cah-${var.region}-admins"
+  name     = "cah-${local.resource_key}-admins"
   user_ids = var.admin_user_ids
 }
 
 resource "twingate_resource" "connector_a_ssh" {
-  name              = "cah-${var.region}-connector-a-ssh"
+  name              = "cah-${local.resource_key}-connector-a-ssh"
   address           = module.connector_a.private_ip
   remote_network_id = twingate_remote_network.this.id
 
@@ -124,7 +131,7 @@ resource "twingate_resource" "connector_a_ssh" {
 }
 
 resource "twingate_resource" "connector_b_ssh" {
-  name              = "cah-${var.region}-connector-b-ssh"
+  name              = "cah-${local.resource_key}-connector-b-ssh"
   address           = module.connector_b.private_ip
   remote_network_id = twingate_remote_network.this.id
 

+ 57 - 0
stacks/10-access/terraform.tfvars.example

@@ -0,0 +1,57 @@
+# Example values for stacks/10-access. Copy this file to terraform.tfvars
+# (which git ignores) for a local plan. Never put a token, key or password in a
+# value file: those live in Doppler. Every value here is a placeholder, not a
+# real one. In the live stack the first five arrive as TF_VAR_* from the
+# foundation stack's outputs and the Spacelift environment, and the rest from
+# Doppler through the Spacelift hook.
+#
+# Droplet sizes are not set here. They live in cost.json, so the cost gate stays
+# the one place that prices them (see docs/cost.md).
+
+# DigitalOcean region slug, from the foundation stack's region output.
+region = "tor1"
+
+# Id of the VPC the connectors join, from the foundation stack's vpc_id output.
+vpc_id = "vpc-example-0000"
+
+# Id of the DigitalOcean project, from the foundation stack's project_id output.
+project_id = "project-example-0000"
+
+# Baseline firewall tag, from the foundation stack's baseline_tag output. It must
+# start with "cah-baseline-" so the baseline firewall covers the connectors.
+baseline_tag = "cah-baseline-tor1"
+
+# Bare Twingate network subdomain (only the part before the Twingate domain). Private: it
+# identifies your tenant, so the real one comes from Doppler.
+twingate_network = "example-tenant"
+
+# Public SSH key for the cah-admin user: "<algorithm> <key>" with an optional
+# one-word comment. The comment is dropped before the key reaches the droplet.
+# This placeholder is deliberately not a real key. The real one comes from Doppler.
+admin_ssh_public_key = "ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY example-key"
+
+# Name of an SSH key already registered on the DigitalOcean account (it is looked
+# up, never registered). The real name comes from Doppler.
+admin_ssh_key_name = "example-admin-key"
+
+# Twingate user ids placed in the admin group (at least one). The real ids come
+# from Doppler.
+admin_user_ids = ["example-user-id"]
+
+# When each connector may reboot, HH:MM in America/New_York (the droplet's local
+# time). Keys a and b. The two times must be at least 60 minutes apart around the
+# clock (across midnight too), so the connectors never reboot together and the
+# weekly update, 30 minutes after each reboot, stays clear of the other reboot.
+# These are the times the live connectors use.
+reboot_times = { a = "04:00", b = "05:00" }
+
+# Used in the NAMES and TAGS of cloud and Twingate objects (access-<key>,
+# cah-connector-<key>, droplet names). Empty means region, so every name is the
+# same as before this setting existed. IMMUTABLE for the life of a stack:
+# changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data including the connectors.
+# Set it only on a NEW stack, and use the same value as the foundation stack.
+resource_key = ""
+
+# A label for telemetry only (empty means "site-<region>"). It appears in no
+# resource name, tag or output, and changing it replaces nothing.
+site_name = "site-tor1"

+ 446 - 2
stacks/10-access/tests/access.tftest.hcl

@@ -287,8 +287,8 @@ run "an_empty_admin_list_is_rejected" {
 run "the_two_connectors_reboot_at_different_times" {
   command = plan
   assert {
-    condition     = length(regexall("reboot_time\\s*=\\s*\"04:00\"", file("${path.module}/main.tf"))) == 1 && length(regexall("reboot_time\\s*=\\s*\"05:00\"", file("${path.module}/main.tf"))) == 1
-    error_message = "Connector a must reboot at 04:00 and connector b at 05:00 Eastern, so they never reboot together."
+    condition     = length(regexall("reboot_time\\s*=\\s*var.reboot_times\\[\"a\"\\]", file("${path.module}/main.tf"))) == 1 && length(regexall("reboot_time\\s*=\\s*var.reboot_times\\[\"b\"\\]", file("${path.module}/main.tf"))) == 1
+    error_message = "Connector a must take reboot_times[\"a\"] and connector b reboot_times[\"b\"]."
   }
   assert {
     condition     = length(regexall("reboot_time\\s*=", file("${path.module}/main.tf"))) == 2
@@ -298,4 +298,448 @@ run "the_two_connectors_reboot_at_different_times" {
     condition     = length(regexall("admin_ssh_public_key\\s*=\\s*var.admin_ssh_public_key", file("${path.module}/main.tf"))) == 2
     error_message = "Both connectors must receive the admin public key."
   }
+  assert {
+    condition     = var.reboot_times["a"] == "04:00" && var.reboot_times["b"] == "05:00" && var.reboot_times["a"] != var.reboot_times["b"]
+    error_message = "The defaults must be the times the live connectors use today: 04:00 and 05:00 Eastern."
+  }
+}
+
+# --- golden names ------------------------------------------------------------
+# The names the live stack has today, with the default settings.
+
+run "golden_names_with_defaults" {
+  command = plan
+  assert {
+    condition     = twingate_remote_network.this.name == "access-tor1"
+    error_message = "The Twingate remote network name changed."
+  }
+  assert {
+    condition     = digitalocean_tag.connector.name == "cah-connector-tor1"
+    error_message = "The connector tag name changed."
+  }
+  assert {
+    condition     = twingate_group.admins.name == "cah-tor1-admins"
+    error_message = "The admin group name changed."
+  }
+  assert {
+    condition     = twingate_resource.connector_a_ssh.name == "cah-tor1-connector-a-ssh" && twingate_resource.connector_b_ssh.name == "cah-tor1-connector-b-ssh"
+    error_message = "A Twingate SSH resource name changed."
+  }
+  assert {
+    condition     = module.connector_a.droplet_name == "access-tor1-connector-a" && module.connector_b.droplet_name == "access-tor1-connector-b"
+    error_message = "A droplet name changed."
+  }
+  assert {
+    condition     = module.connector_firewall.name == "access-tor1-connector"
+    error_message = "The connector firewall name changed."
+  }
+  assert {
+    condition     = output.connector_tag == "cah-connector-tor1"
+    error_message = "The connector_tag output changed."
+  }
+}
+
+run "an_empty_resource_key_means_the_region" {
+  command = plan
+  variables {
+    resource_key = ""
+  }
+  assert {
+    condition = alltrue([
+      twingate_remote_network.this.name == "access-tor1",
+      digitalocean_tag.connector.name == "cah-connector-tor1",
+      twingate_group.admins.name == "cah-tor1-admins",
+      twingate_resource.connector_a_ssh.name == "cah-tor1-connector-a-ssh",
+      twingate_resource.connector_b_ssh.name == "cah-tor1-connector-b-ssh",
+      module.connector_a.droplet_name == "access-tor1-connector-a",
+      module.connector_b.droplet_name == "access-tor1-connector-b",
+      module.connector_firewall.name == "access-tor1-connector",
+    ])
+    error_message = "An empty resource_key must leave every name as it is today."
+  }
+}
+
+run "resource_key_names_every_object_and_the_region_stays_the_region" {
+  command = plan
+  variables {
+    resource_key = "tor1-b"
+  }
+  assert {
+    condition = alltrue([
+      twingate_remote_network.this.name == "access-tor1-b",
+      digitalocean_tag.connector.name == "cah-connector-tor1-b",
+      twingate_group.admins.name == "cah-tor1-b-admins",
+      twingate_resource.connector_a_ssh.name == "cah-tor1-b-connector-a-ssh",
+      twingate_resource.connector_b_ssh.name == "cah-tor1-b-connector-b-ssh",
+      module.connector_a.droplet_name == "access-tor1-b-connector-a",
+      module.connector_b.droplet_name == "access-tor1-b-connector-b",
+      module.connector_firewall.name == "access-tor1-b-connector",
+    ])
+    error_message = "A resource_key must replace the region in every name."
+  }
+  assert {
+    condition     = length(regexall("region\\s*=\\s*var.region", file("${path.module}/main.tf"))) == 3
+    error_message = "The two connector modules and the firewall module must still receive the real region."
+  }
+  assert {
+    condition     = length(regexall("(?m)resource_key\\s*=\\s*var.resource_key$", file("${path.module}/main.tf"))) == 3
+    error_message = "The two connector modules and the firewall module must receive the resource_key."
+  }
+  assert {
+    condition     = !strcontains(file("${path.module}/main.tf"), "-$${var.region}")
+    error_message = "No name may be built from var.region directly; use local.resource_key."
+  }
+}
+
+run "site_name_changes_no_name" {
+  command = plan
+  variables {
+    site_name = "site-tor1"
+  }
+  assert {
+    condition = alltrue([
+      twingate_remote_network.this.name == "access-tor1",
+      digitalocean_tag.connector.name == "cah-connector-tor1",
+      twingate_group.admins.name == "cah-tor1-admins",
+      module.connector_a.droplet_name == "access-tor1-connector-a",
+      module.connector_firewall.name == "access-tor1-connector",
+    ])
+    error_message = "site_name is a telemetry label and must change no name."
+  }
+}
+
+run "no_source_file_uses_site_name" {
+  command = plan
+  assert {
+    condition     = !strcontains(file("${path.module}/main.tf"), "site_name") && !strcontains(file("${path.module}/outputs.tf"), "site_name")
+    error_message = "site_name must not appear in main.tf or outputs.tf: it is for telemetry labels only."
+  }
+}
+
+run "resource_key_rejects_uppercase" {
+  command = plan
+  variables {
+    resource_key = "Tor1"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_a_leading_digit" {
+  command = plan
+  variables {
+    resource_key = "1tor"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_one_character" {
+  command = plan
+  variables {
+    resource_key = "a"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_25_characters" {
+  command = plan
+  variables {
+    resource_key = "abcdefghijklmnopqrstuvwxy"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "resource_key_rejects_a_space" {
+  command = plan
+  variables {
+    resource_key = "tor 1"
+  }
+  expect_failures = [var.resource_key]
+}
+
+run "site_name_rejects_uppercase" {
+  command = plan
+  variables {
+    site_name = "Site-Tor1"
+  }
+  expect_failures = [var.site_name]
+}
+
+run "site_name_rejects_a_leading_hyphen" {
+  command = plan
+  variables {
+    site_name = "-site"
+  }
+  expect_failures = [var.site_name]
+}
+
+# --- region ------------------------------------------------------------------
+
+run "region_rejects_uppercase" {
+  command = plan
+  variables {
+    region = "Tor1"
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_a_city_name" {
+  command = plan
+  variables {
+    region = "toronto"
+  }
+  expect_failures = [var.region]
+}
+
+run "region_rejects_empty" {
+  command = plan
+  variables {
+    region = ""
+  }
+  expect_failures = [var.region]
+}
+
+# --- reboot_times ------------------------------------------------------------
+
+run "reboot_times_default_to_the_live_values" {
+  command = plan
+  assert {
+    condition     = jsonencode(var.reboot_times) == jsonencode({ a = "04:00", b = "05:00" })
+    error_message = "The default reboot_times must be a = 04:00 and b = 05:00."
+  }
+}
+
+run "reboot_times_accepts_other_distinct_times" {
+  command = plan
+  variables {
+    reboot_times = { a = "03:15", b = "23:59" }
+  }
+  assert {
+    condition     = var.reboot_times["b"] == "23:59"
+    error_message = "Two distinct valid times must be accepted."
+  }
+}
+
+run "reboot_times_exactly_60_minutes_apart_pass" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", b = "05:00" }
+  }
+  assert {
+    condition     = var.reboot_times["b"] == "05:00"
+    error_message = "Exactly 60 minutes apart must be accepted."
+  }
+}
+
+run "reboot_times_60_apart_across_midnight_pass" {
+  command = plan
+  variables {
+    reboot_times = { a = "23:30", b = "00:30" }
+  }
+  assert {
+    condition     = var.reboot_times["a"] == "23:30"
+    error_message = "60 minutes apart across midnight must be accepted."
+  }
+}
+
+run "reboot_times_60_apart_across_midnight_pass_reversed" {
+  command = plan
+  variables {
+    reboot_times = { a = "00:30", b = "23:30" }
+  }
+  assert {
+    condition     = var.reboot_times["b"] == "23:30"
+    error_message = "60 minutes apart across midnight must be accepted either way round."
+  }
+}
+
+run "reboot_times_accepts_the_times_swapped" {
+  command = plan
+  variables {
+    reboot_times = { a = "05:00", b = "04:00" }
+  }
+  assert {
+    condition     = var.reboot_times["a"] == "05:00"
+    error_message = "Swapped times are still distinct."
+  }
+}
+
+run "reboot_times_rejects_identical_times" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", b = "04:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_a_bad_hour" {
+  command = plan
+  variables {
+    reboot_times = { a = "24:00", b = "05:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_a_bad_minute" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", b = "05:60" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_no_zero_pad" {
+  command = plan
+  variables {
+    reboot_times = { a = "4:00", b = "05:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_seconds" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00:00", b = "05:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_a_missing_key" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_an_extra_key" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", b = "05:00", c = "06:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_wrong_keys" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", c = "05:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_rejects_an_empty_map" {
+  command = plan
+  variables {
+    reboot_times = {}
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_reject_one_minute_apart" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", b = "04:01" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_reject_59_minutes_apart" {
+  command = plan
+  variables {
+    reboot_times = { a = "04:00", b = "04:59" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_reject_across_midnight_one_minute_apart" {
+  command = plan
+  variables {
+    reboot_times = { a = "23:59", b = "00:00" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_reject_across_midnight_59_apart" {
+  command = plan
+  variables {
+    reboot_times = { a = "23:31", b = "00:30" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+run "reboot_times_reject_across_midnight_59_apart_reversed" {
+  command = plan
+  variables {
+    reboot_times = { a = "00:30", b = "23:31" }
+  }
+  expect_failures = [var.reboot_times]
+}
+
+# --- admin_ssh_public_key ----------------------------------------------------
+
+run "admin_key_accepts_a_comment_at_the_stack" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest laptop-2026"
+  }
+  assert {
+    condition     = module.connector_a.droplet_name == "access-tor1-connector-a"
+    error_message = "A key with a trailing comment must plan at the stack."
+  }
+}
+
+run "admin_key_rejects_a_two_word_comment" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA two words"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_newline" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA\n  - evil"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_a_trailing_newline" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA\n"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_unsafe_comment_characters" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-ed25519 AAAA user;id"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_an_unknown_algorithm" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "ssh-dss AAAA"
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_an_empty_key" {
+  command = plan
+  variables {
+    admin_ssh_public_key = ""
+  }
+  expect_failures = [var.admin_ssh_public_key]
+}
+
+run "admin_key_rejects_an_option_prefix" {
+  command = plan
+  variables {
+    admin_ssh_public_key = "command=\"id\" ssh-ed25519 AAAA"
+  }
+  expect_failures = [var.admin_ssh_public_key]
 }

+ 77 - 0
stacks/10-access/tests/example.tftest.hcl

@@ -0,0 +1,77 @@
+# GENERATED from terraform.tfvars.example by scripts/gen_example_tests.py. Do not
+# edit by hand: change the example file and run
+# `python -I scripts/gen_example_tests.py`. CI fails when this file is stale.
+# It plans the stack with the example values, so the example stays valid.
+
+mock_provider "digitalocean" {
+  mock_data "digitalocean_ssh_key" {
+    defaults = {
+      fingerprint = "aa:bb:cc:dd:ee:ff"
+    }
+  }
+}
+mock_provider "twingate" {}
+
+variables {
+  # Example values for stacks/10-access. Copy this file to terraform.tfvars
+  # (which git ignores) for a local plan. Never put a token, key or password in a
+  # value file: those live in Doppler. Every value here is a placeholder, not a
+  # real one. In the live stack the first five arrive as TF_VAR_* from the
+  # foundation stack's outputs and the Spacelift environment, and the rest from
+  # Doppler through the Spacelift hook.
+  #
+  # Droplet sizes are not set here. They live in cost.json, so the cost gate stays
+  # the one place that prices them (see docs/cost.md).
+
+  # DigitalOcean region slug, from the foundation stack's region output.
+  region = "tor1"
+
+  # Id of the VPC the connectors join, from the foundation stack's vpc_id output.
+  vpc_id = "vpc-example-0000"
+
+  # Id of the DigitalOcean project, from the foundation stack's project_id output.
+  project_id = "project-example-0000"
+
+  # Baseline firewall tag, from the foundation stack's baseline_tag output. It must
+  # start with "cah-baseline-" so the baseline firewall covers the connectors.
+  baseline_tag = "cah-baseline-tor1"
+
+  # Bare Twingate network subdomain (only the part before the Twingate domain). Private: it
+  # identifies your tenant, so the real one comes from Doppler.
+  twingate_network = "example-tenant"
+
+  # Public SSH key for the cah-admin user: "<algorithm> <key>" with an optional
+  # one-word comment. The comment is dropped before the key reaches the droplet.
+  # This placeholder is deliberately not a real key. The real one comes from Doppler.
+  admin_ssh_public_key = "ssh-ed25519 AAAAEXAMPLEONLYNOTAREALKEY example-key"
+
+  # Name of an SSH key already registered on the DigitalOcean account (it is looked
+  # up, never registered). The real name comes from Doppler.
+  admin_ssh_key_name = "example-admin-key"
+
+  # Twingate user ids placed in the admin group (at least one). The real ids come
+  # from Doppler.
+  admin_user_ids = ["example-user-id"]
+
+  # When each connector may reboot, HH:MM in America/New_York (the droplet's local
+  # time). Keys a and b. The two times must be at least 60 minutes apart around the
+  # clock (across midnight too), so the connectors never reboot together and the
+  # weekly update, 30 minutes after each reboot, stays clear of the other reboot.
+  # These are the times the live connectors use.
+  reboot_times = { a = "04:00", b = "05:00" }
+
+  # Used in the NAMES and TAGS of cloud and Twingate objects (access-<key>,
+  # cah-connector-<key>, droplet names). Empty means region, so every name is the
+  # same as before this setting existed. IMMUTABLE for the life of a stack:
+  # changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data including the connectors.
+  # Set it only on a NEW stack, and use the same value as the foundation stack.
+  resource_key = ""
+
+  # A label for telemetry only (empty means "site-<region>"). It appears in no
+  # resource name, tag or output, and changing it replaces nothing.
+  site_name = "site-tor1"
+}
+
+run "the_example_values_are_valid" {
+  command = plan
+}

+ 71 - 2
stacks/10-access/variables.tf

@@ -1,5 +1,11 @@
 variable "region" {
-  type = string
+  type        = string
+  description = "DigitalOcean region slug, from the foundation stack's region output. Names are built from resource_key, which defaults to this value."
+
+  validation {
+    condition     = can(regex("^[a-z]{3}[0-9]$", var.region))
+    error_message = "region must be a DigitalOcean region slug: three lowercase letters and a digit, for example tor1."
+  }
 }
 
 variable "vpc_id" {
@@ -30,7 +36,13 @@ variable "twingate_network" {
 }
 
 variable "admin_ssh_public_key" {
-  type = string
+  type        = string
+  description = "Public key for the cah-admin user: '<algorithm> <key>' with an optional trailing comment of one word of safe characters. The comment is dropped before the key reaches cloud-init. Supplied from Doppler."
+
+  validation {
+    condition     = can(regex("^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)) [A-Za-z0-9+/]+=*( [A-Za-z0-9@._+:=/-]{1,64})?$", var.admin_ssh_public_key))
+    error_message = "admin_ssh_public_key must be '<ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|384|521> <base64 key>' with at most one trailing comment word of letters, digits and @ . _ + : = / - (no spaces or line breaks)."
+  }
 }
 
 variable "admin_ssh_key_name" {
@@ -52,3 +64,60 @@ variable "admin_user_ids" {
     error_message = "admin_user_ids must list at least one Twingate user. A missing Doppler value would otherwise create a host nobody can reach."
   }
 }
+
+variable "reboot_times" {
+  type = map(string)
+  default = {
+    a = "04:00"
+    b = "05:00"
+  }
+  description = "HH:MM (America/New_York, the droplet's local time) when unattended-upgrades may reboot each connector. Keys a and b. The two times must be at least 60 minutes apart around the clock (across midnight too), so the connectors never reboot together and each weekly update, which runs 30 minutes after its connector's reboot, stays at least 30 minutes from the other connector's reboot."
+
+  validation {
+    condition     = length(var.reboot_times) == 2 && alltrue([for k in ["a", "b"] : contains(keys(var.reboot_times), k)])
+    error_message = "reboot_times must have exactly the keys a and b."
+  }
+
+  validation {
+    condition     = alltrue([for v in values(var.reboot_times) : can(regex("^([01][0-9]|2[0-3]):[0-5][0-9]$", v))])
+    error_message = "Every reboot_times value must be HH:MM in 24-hour time, for example 04:00."
+  }
+
+  # Minutes since midnight for a and b, then the circular distance (the shorter
+  # way round the clock) between: the two reboots (at least 60), and each
+  # connector's update (reboot + 30) against the other's reboot (at least 30).
+  validation {
+    condition = try([
+      for m in [[for k in ["a", "b"] : tonumber(substr(var.reboot_times[k], 0, 2)) * 60 + tonumber(substr(var.reboot_times[k], 3, 2))]] :
+      min(abs(m[0] - m[1]), 1440 - abs(m[0] - m[1])) >= 60 &&
+      min(abs(((m[0] + 30) % 1440) - m[1]), 1440 - abs(((m[0] + 30) % 1440) - m[1])) >= 30 &&
+      min(abs(((m[1] + 30) % 1440) - m[0]), 1440 - abs(((m[1] + 30) % 1440) - m[0])) >= 30
+    ][0], false)
+    error_message = "The reboot_times must be at least 60 minutes apart around the clock (23:30 and 00:30 are 60 apart), so the connectors never reboot together and a weekly update never lands within 30 minutes of the other connector's reboot."
+  }
+}
+
+variable "resource_key" {
+  type        = string
+  default     = ""
+  description = "Key used in the NAMES and TAGS of cloud and Twingate objects (access-<key>, cah-connector-<key>, droplet names). Empty means region, so every name is identical to a stack that never set it. IMMUTABLE FOR THE LIFE OF A STACK: changing it changes names, causes widespread plan changes and may replace resources, including through tags or user_data. A second site in the same region sets its own key on a NEW stack only. Never derived from site_name."
+
+  validation {
+    condition     = var.resource_key == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.resource_key))
+    error_message = "resource_key must be empty (meaning region) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}
+
+# Declared for the telemetry stage (stack 20) and deliberately used by no resource,
+# name, tag or output until then; wiring it in would show as a plan change.
+# tflint-ignore: terraform_unused_declarations
+variable "site_name" {
+  type        = string
+  default     = ""
+  description = "Telemetry label only (metrics and log labels in a later stage). Empty means site-<region>. Appears in no resource name, tag or output, and changing it replaces nothing. Unique across your sites."
+
+  validation {
+    condition     = var.site_name == "" || can(regex("^[a-z][a-z0-9-]{1,23}$", var.site_name))
+    error_message = "site_name must be empty (meaning site-<region>) or 2 to 24 characters: a lowercase letter, then lowercase letters, digits or hyphens."
+  }
+}

+ 574 - 0
tests/test_plan_noop_check.py

@@ -0,0 +1,574 @@
+"""scripts/plan_noop_check.py against mocked plan JSON, and the golden files.
+
+CI cannot run a real plan (that needs the live state and credentials), so the
+checker is proved here against plan JSON built from the golden files: a no-op
+plan passes, and every kind of change the stage 2 settings work must never
+cause (a rename, an update, a replacement, a missing or extra address, a moved
+resource, a changed force-new attribute) fails. The real gate is the
+tracked-run plan the maintainer reads in Spacelift.
+
+The golden files are also tied to the code: the addresses must equal the ones
+derived from the stack sources and module calls, and the bootstrap `moved`
+blocks must be the moves the files list.
+"""
+
+import copy
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "scripts"))
+import plan_noop_check as pnc
+
+GOLDEN_DIR = ROOT / "docs" / "golden-addresses"
+STACKS = ("00-foundation", "10-access")
+SECRET_MARKER = "TOKEN-MARKER-must-never-be-printed"
+
+
+def load_golden(stack: str) -> dict:
+    return json.loads((GOLDEN_DIR / f"{stack}.json").read_text(encoding="utf-8"))
+
+
+def attribute_value(attr: str, expected):
+    return f"id-of-{attr}" if expected == pnc.UNCHANGED else copy.deepcopy(expected)
+
+
+def noop_plan(golden: dict) -> dict:
+    """A plan JSON shaped like `tofu show -json`, where nothing changes."""
+    changes = []
+    for address, spec in golden["addresses"].items():
+        values = {a: attribute_value(a, v) for a, v in spec["force_new"].items()}
+        values["some_other_attribute"] = "x"
+        changes.append(
+            {
+                "address": address,
+                "mode": "managed",
+                "type": spec["type"],
+                "change": {
+                    "actions": ["no-op"],
+                    "before": dict(values),
+                    "after": dict(values),
+                    "after_unknown": {},
+                },
+            }
+        )
+    for address in golden.get("data", []):
+        changes.append(
+            {
+                "address": address,
+                "mode": "data",
+                "type": "digitalocean_ssh_key",
+                "change": {"actions": ["read"], "before": None, "after": {}},
+            }
+        )
+    return {"format_version": "1.2", "resource_changes": changes}
+
+
+def entry(plan: dict, address: str) -> dict:
+    return next(e for e in plan["resource_changes"] if e["address"] == address)
+
+
+def run(plan: dict, golden: dict, allow_moves: bool = False) -> list[str]:
+    return pnc.check(plan, golden, allow_moves)
+
+
+# --- a no-op plan passes ----------------------------------------------------
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_a_noop_plan_passes(stack):
+    golden = load_golden(stack)
+    assert run(noop_plan(golden), golden) == []
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_a_noop_plan_passes_with_allow_moves(stack):
+    golden = load_golden(stack)
+    assert run(noop_plan(golden), golden, allow_moves=True) == []
+
+
+def test_tag_order_does_not_matter():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    droplet = entry(plan, "module.connector_a.digitalocean_droplet.connector")["change"]
+    droplet["after"]["tags"] = list(reversed(droplet["after"]["tags"]))
+    assert run(plan, golden) == []
+
+
+def test_a_data_source_read_at_plan_time_may_be_absent():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    plan["resource_changes"] = [
+        e for e in plan["resource_changes"] if e.get("mode") != "data"
+    ]
+    assert run(plan, golden) == []
+
+
+# --- what must fail -----------------------------------------------------------
+
+
+def test_renaming_the_remote_network_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    change = entry(plan, "twingate_remote_network.this")["change"]
+    change["before"]["name"] = "access-tor1"
+    change["after"]["name"] = "access-site-tor1"
+    change["actions"] = ["update"]
+    problems = "\n".join(run(plan, golden))
+    assert "twingate_remote_network.this" in problems
+    assert "action is ['update']" in problems
+    assert "attribute name differs" in problems
+
+
+def test_a_rename_hidden_behind_a_noop_action_still_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    change = entry(plan, "twingate_remote_network.this")["change"]
+    change["after"]["name"] = "access-site-tor1"
+    problems = run(plan, golden)
+    assert any("attribute name differs" in p for p in problems), problems
+
+
+def test_a_rename_present_on_both_sides_is_not_the_golden_value():
+    # What a changed default does to a brand new stack: before and after agree,
+    # but they are not the names the live stack has.
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    change = entry(plan, "twingate_remote_network.this")["change"]
+    change["before"]["name"] = change["after"]["name"] = "access-site-tor1"
+    problems = run(plan, golden)
+    assert any("not the golden value" in p for p in problems), problems
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_an_update_fails(stack):
+    golden = load_golden(stack)
+    for address in golden["addresses"]:
+        plan = noop_plan(golden)
+        entry(plan, address)["change"]["actions"] = ["update"]
+        problems = run(plan, golden)
+        assert any(address in p and "action is ['update']" in p for p in problems), (
+            address,
+            problems,
+        )
+
+
+@pytest.mark.parametrize(
+    "actions", [["create"], ["delete"], ["delete", "create"], ["create", "delete"], []]
+)
+def test_create_delete_and_replace_fail(actions):
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    entry(plan, "module.connector_a.digitalocean_droplet.connector")["change"][
+        "actions"
+    ] = actions
+    assert run(plan, golden)
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_a_missing_address_fails(stack):
+    golden = load_golden(stack)
+    for address in golden["addresses"]:
+        plan = noop_plan(golden)
+        plan["resource_changes"] = [
+            e for e in plan["resource_changes"] if e["address"] != address
+        ]
+        problems = run(plan, golden)
+        assert any(
+            address in p and "missing from the plan" in p for p in problems
+        ), (address, problems)
+
+
+def test_an_address_not_in_the_golden_list_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    plan["resource_changes"].append(
+        {
+            "address": "digitalocean_droplet.surprise",
+            "mode": "managed",
+            "type": "digitalocean_droplet",
+            "change": {"actions": ["no-op"], "before": {}, "after": {}},
+        }
+    )
+    problems = run(plan, golden)
+    assert any("digitalocean_droplet.surprise" in p and "not in the golden" in p for p in problems)
+
+
+def test_a_data_source_not_in_the_golden_list_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    plan["resource_changes"].append(
+        {
+            "address": "data.digitalocean_ssh_key.other",
+            "mode": "data",
+            "type": "digitalocean_ssh_key",
+            "change": {"actions": ["read"], "before": None, "after": {}},
+        }
+    )
+    assert any("data.digitalocean_ssh_key.other" in p for p in run(plan, golden))
+
+
+def test_a_data_source_that_would_be_created_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    entry(plan, "data.digitalocean_ssh_key.admin")["change"]["actions"] = ["create"]
+    assert run(plan, golden)
+
+
+def test_the_same_address_twice_fails():
+    golden = load_golden("00-foundation")
+    plan = noop_plan(golden)
+    plan["resource_changes"].append(copy.deepcopy(plan["resource_changes"][0]))
+    assert any("appears twice" in p for p in run(plan, golden))
+
+
+def force_new_cases():
+    for stack in STACKS:
+        golden = load_golden(stack)
+        for address, spec in golden["addresses"].items():
+            for attr in spec["force_new"]:
+                yield stack, address, attr
+
+
+@pytest.mark.parametrize("stack,address,attr", list(force_new_cases()))
+def test_every_force_new_attribute_is_compared(stack, address, attr):
+    golden = load_golden(stack)
+    plan = noop_plan(golden)
+    change = entry(plan, address)["change"]
+    value = change["after"][attr]
+    if isinstance(value, bool):
+        change["after"][attr] = not value
+    elif isinstance(value, list):
+        change["after"][attr] = [*value, "extra"]
+    else:
+        change["after"][attr] = f"{value}-changed"
+    problems = run(plan, golden)
+    assert any(address in p and attr in p for p in problems), problems
+
+
+@pytest.mark.parametrize("stack,address,attr", list(force_new_cases()))
+def test_every_force_new_attribute_must_be_present_and_known(stack, address, attr):
+    golden = load_golden(stack)
+    plan = noop_plan(golden)
+    del entry(plan, address)["change"]["before"][attr]
+    assert any(address in p and attr in p for p in run(plan, golden))
+    plan = noop_plan(golden)
+    entry(plan, address)["change"]["after_unknown"] = {attr: True}
+    assert any(address in p and attr in p for p in run(plan, golden))
+
+
+def test_a_changed_user_data_fails_without_printing_it(tmp_path, capsys):
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    change = entry(plan, "module.connector_a.digitalocean_droplet.connector")["change"]
+    change["before"]["user_data"] = f"before {SECRET_MARKER}"
+    change["after"]["user_data"] = f"after {SECRET_MARKER}"
+    (tmp_path / "plan.json").write_text(json.dumps(plan))
+    code = pnc.main(
+        ["--plan", str(tmp_path / "plan.json"), "--golden", str(GOLDEN_DIR / "10-access.json")]
+    )
+    captured = capsys.readouterr()
+    assert code == 1
+    assert "user_data" in captured.out
+    assert SECRET_MARKER not in captured.out + captured.err
+
+
+# --- moves -------------------------------------------------------------------
+
+
+def moved_plan():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    for new, old in (
+        (
+            "module.connector_a.module.bootstrap.twingate_connector.this",
+            "module.connector_a.twingate_connector.this",
+        ),
+    ):
+        entry(plan, new)["previous_address"] = old
+    return golden, plan
+
+
+def test_a_moved_resource_fails_without_allow_moves():
+    golden, plan = moved_plan()
+    assert any("moved" in p for p in run(plan, golden))
+
+
+def test_a_moved_resource_passes_with_allow_moves_when_listed():
+    golden, plan = moved_plan()
+    assert run(plan, golden, allow_moves=True) == []
+
+
+def test_a_move_from_an_unlisted_address_fails_even_with_allow_moves():
+    golden, plan = moved_plan()
+    entry(plan, "module.connector_a.module.bootstrap.twingate_connector.this")[
+        "previous_address"
+    ] = "twingate_connector.elsewhere"
+    assert any("does not allow" in p for p in run(plan, golden, allow_moves=True))
+
+
+def test_allow_moves_does_not_excuse_a_changed_attribute():
+    golden, plan = moved_plan()
+    change = entry(plan, "module.connector_a.module.bootstrap.twingate_connector.this")["change"]
+    change["after"]["name"] = "access-site-tor1-connector-a"
+    assert run(plan, golden, allow_moves=True)
+
+
+# --- the files it reads ------------------------------------------------------
+
+
+def write(tmp_path, plan, golden=None):
+    (tmp_path / "plan.json").write_text(json.dumps(plan))
+    (tmp_path / "golden.json").write_text(json.dumps(golden or load_golden("00-foundation")))
+    return ["--plan", str(tmp_path / "plan.json"), "--golden", str(tmp_path / "golden.json")]
+
+
+def test_main_exit_codes(tmp_path, capsys):
+    golden = load_golden("00-foundation")
+    assert pnc.main(write(tmp_path, noop_plan(golden))) == 0
+    bad = noop_plan(golden)
+    entry(bad, "digitalocean_tag.baseline")["change"]["actions"] = ["update"]
+    assert pnc.main(write(tmp_path, bad)) == 1
+
+
+def test_main_refuses_unusable_input(tmp_path, capsys):
+    golden = load_golden("00-foundation")
+    args = write(tmp_path, noop_plan(golden))
+    assert pnc.main(["--plan", str(tmp_path / "nope.json"), "--golden", args[3]]) == 2
+    (tmp_path / "plan.json").write_text("{not json")
+    assert pnc.main(args) == 2
+    (tmp_path / "plan.json").write_text("[]")
+    assert pnc.main(args) == 2
+    # a plan with no resource_changes is not a plan we can judge: fail, never pass
+    (tmp_path / "plan.json").write_text(json.dumps({"format_version": "1.2"}))
+    assert pnc.main(args) == 2
+    (tmp_path / "plan.json").write_text(
+        json.dumps({"errored": True, "resource_changes": []})
+    )
+    assert pnc.main(args) == 2
+    (tmp_path / "plan.json").write_text(json.dumps({"resource_changes": ["x"]}))
+    assert pnc.main(args) == 2
+    capsys.readouterr()
+
+
+@pytest.mark.parametrize(
+    "mutate",
+    [
+        lambda g: g.update(addresses={}),
+        lambda g: g.update(extra=1),
+        lambda g: g["addresses"]["digitalocean_tag.baseline"].update(force_new={}),
+        lambda g: g["addresses"]["digitalocean_tag.baseline"].pop("type"),
+        lambda g: g.update(moves={"a": "not.listed"}),
+        lambda g: g.update(data="x"),
+        lambda g: g.pop("stack"),
+    ],
+)
+def test_a_malformed_golden_file_is_refused(tmp_path, mutate):
+    golden = load_golden("00-foundation")
+    mutate(golden)
+    args = write(tmp_path, noop_plan(load_golden("00-foundation")), golden)
+    assert pnc.main(args) == 2
+
+
+def test_running_as_a_script_with_isolated_mode(tmp_path):
+    golden = load_golden("00-foundation")
+    args = write(tmp_path, noop_plan(golden))
+    result = subprocess.run(
+        [sys.executable, "-I", str(ROOT / "scripts" / "plan_noop_check.py"), *args],
+        capture_output=True,
+        text=True,
+        check=False,
+    )
+    assert result.returncode == 0, result.stderr
+    assert "passed" in result.stdout
+
+
+# --- the golden files match the code -------------------------------------------
+
+
+def top_level_blocks(text: str):
+    """(kind, labels, body) for each top-level block; blocks end at a line '}'."""
+    for m in re.finditer(r'(?ms)^(\w+)((?:\s+"[^"]+")*)\s*\{\n(.*?)^\}\n', text):
+        yield m.group(1), re.findall(r'"([^"]+)"', m.group(2)), m.group(3)
+
+
+def derive(directory: Path, prefix: str = "") -> tuple[set[str], set[str]]:
+    """Resource and data addresses a directory creates, including its modules."""
+    resources: set[str] = set()
+    data: set[str] = set()
+    for tf in sorted(directory.glob("*.tf")):
+        for kind, labels, body in top_level_blocks(tf.read_text(encoding="utf-8")):
+            if kind == "resource":
+                if re.search(r"(?m)^  (count|for_each)\s*=", body):
+                    raise AssertionError(f"{tf}: count/for_each is not understood here")
+                resources.add(f"{prefix}{labels[0]}.{labels[1]}")
+            elif kind == "data":
+                data.add(f"{prefix}data.{labels[0]}.{labels[1]}")
+            elif kind == "module":
+                if re.search(r"(?m)^  (count|for_each)\s*=", body):
+                    raise AssertionError(f"{tf}: count/for_each is not understood here")
+                source = re.search(r'(?m)^\s*source\s*=\s*"([^"]+)"', body).group(1)
+                sub_r, sub_d = derive(
+                    (directory / source).resolve(), f"{prefix}module.{labels[0]}."
+                )
+                resources |= sub_r
+                data |= sub_d
+    return resources, data
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_the_golden_addresses_are_exactly_what_the_sources_create(stack):
+    golden = load_golden(stack)
+    resources, data = derive(ROOT / "stacks" / stack)
+    assert set(golden["addresses"]) == resources
+    assert set(golden["data"]) == data
+    assert golden["stack"] == f"stacks/{stack}"
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_golden_types_match_the_address(stack):
+    for address, spec in load_golden(stack)["addresses"].items():
+        assert address.split(".")[-2] == spec["type"], address
+
+
+def test_the_golden_moves_are_the_moved_blocks_of_the_connector_module():
+    text = (ROOT / "modules" / "twingate-connector" / "main.tf").read_text()
+    pairs = re.findall(
+        r"(?ms)^moved\s*\{\s*from\s*=\s*(\S+)\s*to\s*=\s*(\S+)\s*\}", text
+    )
+    assert pairs, "no moved blocks found"
+    expected = {}
+    for module in ("connector_a", "connector_b"):
+        for old, new in pairs:
+            expected[f"module.{module}.{old}"] = f"module.{module}.{new}"
+    assert load_golden("10-access")["moves"] == expected
+    assert load_golden("00-foundation")["moves"] == {}
+
+
+def test_the_golden_droplet_size_is_the_costed_size():
+    cost = json.loads((ROOT / "stacks" / "10-access" / "cost.json").read_text())
+    sizes = {r["size"] for r in cost["resources"]}
+    golden = load_golden("10-access")["addresses"]
+    for x in ("a", "b"):
+        spec = golden[f"module.connector_{x}.digitalocean_droplet.connector"]
+        assert {spec["force_new"]["size"]} == sizes
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_every_golden_name_is_asserted_by_the_stack_tests(stack):
+    # The golden file and the stack's own golden-name test must agree, so one
+    # cannot be edited without the other.
+    tests = "\n".join(
+        p.read_text() for p in (ROOT / "stacks" / stack / "tests").glob("*.tftest.hcl")
+    )
+    for address, spec in load_golden(stack)["addresses"].items():
+        name = spec["force_new"].get("name")
+        if name:
+            assert f'"{name}"' in tests, f"{address}: {name} is not asserted in the tests"
+
+
+# --- outputs and data sources (review findings) -----------------------------------
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_a_changed_output_fails_even_when_every_resource_is_noop(stack):
+    golden = load_golden(stack)
+    plan = noop_plan(golden)
+    plan["output_changes"] = {
+        "region": {"actions": ["update"], "before": "tor1", "after": "fra1"}
+    }
+    problems = run(plan, golden)
+    assert any("output region" in p for p in problems), problems
+    assert not any("tor1" in p or "fra1" in p for p in problems)
+
+
+@pytest.mark.parametrize("actions", [["create"], ["delete"], ["update"], []])
+def test_any_output_action_but_noop_fails(actions):
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    plan["output_changes"] = {"connector_tag": {"actions": actions}}
+    assert run(plan, golden)
+
+
+def test_an_unknown_output_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    plan["output_changes"] = {
+        "connector_private_ips": {"actions": ["no-op"], "after_unknown": True}
+    }
+    assert any("unknown" in p for p in run(plan, golden))
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_unchanged_outputs_pass(stack):
+    golden = load_golden(stack)
+    plan = noop_plan(golden)
+    plan["output_changes"] = {
+        "region": {"actions": ["no-op"], "before": "tor1", "after": "tor1"}
+    }
+    assert run(plan, golden) == []
+
+
+def test_a_malformed_output_changes_block_is_refused(tmp_path):
+    golden = load_golden("00-foundation")
+    for bad in ([], {"region": "x"}, {"region": {}}):
+        plan = noop_plan(golden)
+        plan["output_changes"] = bad
+        with pytest.raises(pnc.InputError):
+            run(plan, golden)
+
+
+def test_a_moved_data_source_fails_without_allow_moves():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    entry(plan, "data.digitalocean_ssh_key.admin")["previous_address"] = "data.digitalocean_ssh_key.old"
+    assert any("moved" in p for p in run(plan, golden))
+    # not excused by --allow-moves either: the golden file lists no such move
+    assert any("does not allow" in p for p in run(plan, golden, allow_moves=True))
+
+
+@pytest.mark.parametrize("actions", [["update"], ["delete"], ["delete", "create"]])
+def test_a_data_source_may_not_update_or_delete(actions):
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    entry(plan, "data.digitalocean_ssh_key.admin")["change"]["actions"] = actions
+    assert run(plan, golden)
+
+
+def test_an_updated_baseline_tag_output_on_stack_00_fails():
+    golden = load_golden("00-foundation")
+    plan = noop_plan(golden)
+    plan["output_changes"] = {
+        "baseline_tag": {"actions": ["update"], "before": "cah-baseline-tor1", "after": "x"}
+    }
+    problems = run(plan, golden)
+    assert any("output baseline_tag" in p for p in problems), problems
+
+
+def test_an_updated_connector_output_on_stack_10_fails():
+    golden = load_golden("10-access")
+    plan = noop_plan(golden)
+    plan["output_changes"] = {
+        "connector_tag": {"actions": ["update"], "before": "a", "after": "b"}
+    }
+    assert any("output connector_tag" in p for p in run(plan, golden))
+    plan["output_changes"] = {
+        "connector_private_ips": {"actions": ["create"], "before": None, "after": {}}
+    }
+    assert any("output connector_private_ips" in p for p in run(plan, golden))
+
+
+def test_the_command_line_fails_on_an_output_only_change(tmp_path):
+    golden = load_golden("00-foundation")
+    plan = noop_plan(golden)
+    plan["output_changes"] = {"baseline_tag": {"actions": ["update"]}}
+    (tmp_path / "plan.json").write_text(json.dumps(plan))
+    code = pnc.main(
+        ["--plan", str(tmp_path / "plan.json"), "--golden", str(GOLDEN_DIR / "00-foundation.json")]
+    )
+    assert code == 1

+ 101 - 0
tests/test_resource_key.py

@@ -0,0 +1,101 @@
+"""resource_key and site_name (stage 2 design, section 3.1), checked on the sources.
+
+`resource_key` builds NAMES; `region` is only the region argument. `site_name`
+is a telemetry label and must never reach a resource name, a tag, a `moved`
+target or an output. The tofu tests prove the rendered names; these tests read
+every .tf file, so a name built another way, or a site_name used in a new
+file, fails here too.
+"""
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+
+
+def source_files():
+    """Every .tf file under stacks and modules, except variable declarations."""
+    for top in ("stacks", "modules"):
+        for path in sorted((ROOT / top).rglob("*.tf")):
+            if ".terraform" in path.parts or path.name == "variables.tf":
+                continue
+            # resource_key is DigitalOcean-only for now: stacks/<NN-name> and
+            # modules/<role>. The AWS code (stacks/aws/*, modules/aws/*) still
+            # names from region and has no resource_key; see the PR text.
+            if len(path.relative_to(ROOT / top).parts) > 2:
+                continue
+            yield path
+
+
+def without_comments(text: str) -> str:
+    return re.sub(r"(?m)(#|//).*$", "", text)
+
+
+def test_resource_key_is_digitalocean_only_for_now():
+    # Say so in a test: if an AWS stack or module gains resource_key, this
+    # fails and the scope above must be widened on purpose, with golden names.
+    for path in (ROOT / "stacks" / "aws").rglob("variables.tf"):
+        assert 'variable "resource_key"' not in path.read_text(), path
+    for path in (ROOT / "modules" / "aws").rglob("variables.tf"):
+        assert 'variable "resource_key"' not in path.read_text(), path
+
+
+def test_there_are_source_files_to_check():
+    assert len(list(source_files())) >= 12
+
+
+def test_site_name_is_declared_but_never_used():
+    for path in source_files():
+        assert "site_name" not in without_comments(path.read_text()), (
+            f"{path.relative_to(ROOT)} uses site_name; it is for telemetry labels only"
+        )
+
+
+def test_site_name_is_only_declared_in_the_stacks():
+    declared = [
+        p.parent.relative_to(ROOT).as_posix()
+        for p in (ROOT / "stacks").glob("*/variables.tf")
+        if 'variable "site_name"' in p.read_text()
+    ]
+    assert sorted(declared) == ["stacks/00-foundation", "stacks/10-access"]
+    for path in (ROOT / "modules").glob("*/variables.tf"):
+        assert 'variable "site_name"' not in path.read_text(), path
+
+
+def test_no_name_is_built_from_the_region_directly():
+    # A name must use resource_key (or the modules' name_key). A string that
+    # interpolates var.region would ignore resource_key and rename on change.
+    pattern = re.compile(r"\$\{[^}]*\bvar\.region\b[^}]*\}")
+    for path in source_files():
+        assert not pattern.search(without_comments(path.read_text())), (
+            f"{path.relative_to(ROOT)} interpolates var.region into a string"
+        )
+
+
+def test_region_is_only_used_as_an_argument_or_a_fallback():
+    # Every use of var.region outside variables.tf is either `region = var.region`
+    # (the real region argument) or the resource_key fallback.
+    allowed = re.compile(
+        r"(?m)^\s*region\s*=\s*var\.region\s*$"
+        r"|^\s*value\s*=\s*var\.region\s*$"
+        r"|\?\s*var\.resource_key\s*:\s*var\.region\b"
+        r"|^\s*region\s*=\s*var\.region\b"
+    )
+    for path in source_files():
+        text = without_comments(path.read_text())
+        for line in text.splitlines():
+            if "var.region" in line:
+                assert allowed.search(line), (
+                    f"{path.relative_to(ROOT)}: unexpected use of var.region: {line.strip()}"
+                )
+
+
+def test_resource_key_is_passed_down_next_to_every_region():
+    # Wherever a module call receives the real region it also receives the key.
+    for path in source_files():
+        text = without_comments(path.read_text())
+        for block in re.findall(r"(?ms)^module\s+\"[^\"]+\"\s*\{\n(.*?)^\}\n", text):
+            if re.search(r"(?m)^\s*region\s*=\s*var\.region", block):
+                assert re.search(r"(?m)^\s*resource_key\s*=\s*var\.resource_key\s*$", block), (
+                    f"{path.relative_to(ROOT)}: a module gets region but not resource_key"
+                )

+ 66 - 2
tests/test_settings_manifest.py

@@ -369,10 +369,10 @@ def test_coverage_bites_when_a_validation_is_added_or_dropped(tree):
 
 def test_coverage_bites_when_a_planned_entry_becomes_real(tree):
     with (tree / "stacks" / "00-foundation" / "variables.tf").open("a") as f:
-        f.write('\nvariable "site_name" {\n  type    = string\n  default = ""\n}\n')
+        f.write('\nvariable "provider_name" {\n  type    = string\n  default = "digitalocean"\n}\n')
     problems = coverage_problems(tree, load())
     assert any(
-        "site_name exists in code but the manifest says planned" in p for p in problems
+        "provider_name exists in code but the manifest says planned" in p for p in problems
     ), problems
 
 
@@ -709,3 +709,67 @@ def test_an_example_value_file_can_be_added_to_git(tmp_path):
     )
     assert "terraform.tfvars.example" in add.stdout
     assert "'terraform.tfvars'" not in add.stdout
+
+
+# --- literal values: lists, objects, assignments --------------------------------
+
+
+def test_the_reader_reads_list_and_object_defaults():
+    text = """
+variable "m" {
+  type = map(string)
+  default = {
+    a = "04:00" # a comment after a value
+    "b" = "05:00",
+  }
+}
+variable "l" {
+  type    = list(string)
+  default = ["x", "y", ]
+}
+variable "n" {
+  type    = list(object({ k = number }))
+  default = [{ k = 1 }, { k = 2.5 }]
+}
+"""
+    found = {v.name: v.default for v in hcl_variables.parse_variables(text)}
+    assert found == {
+        "m": {"a": "04:00", "b": "05:00"},
+        "l": ["x", "y"],
+        "n": [{"k": 1}, {"k": 2.5}],
+    }
+
+
+@pytest.mark.parametrize(
+    "default",
+    [
+        '{ a = "x", a = "y" }',  # repeated key
+        '{ a = "x" b = "y" }',  # no separator on one line
+        '["x" "y"]',  # no comma
+        "{ a = var.x }",  # not a literal
+        "[1, foo]",
+        "10.78.0.0",  # an unquoted address is not a number
+        "truely",
+        "[[[[[[[[[[1]]]]]]]]]]",  # nested too deeply
+        '{ a = "x"',  # unbalanced
+    ],
+)
+def test_the_reader_refuses_a_default_it_does_not_understand(default):
+    text = f'variable "a" {{\n  type    = string\n  default = {default}\n}}\n'
+    with pytest.raises(hcl_variables.HclError):
+        hcl_variables.parse_variables(text)
+
+
+def test_parse_assignments_reads_a_value_file():
+    text = (
+        '# c\nregion = "tor1" # why\nlist = ["a",\n  "b"]\n'
+        'map = { a = "1", b = "2" }\nflag = true\nnum = 3\nnone = null\n'
+    )
+    assert hcl_variables.parse_assignments(text) == {
+        "region": "tor1",
+        "list": ["a", "b"],
+        "map": {"a": "1", "b": "2"},
+        "flag": True,
+        "num": 3,
+        "none": None,
+    }

+ 299 - 0
tests/test_tfvars_example.py

@@ -0,0 +1,299 @@
+"""terraform.tfvars.example for each live stack (stage 2 design, section 2.6).
+
+The example is committed documentation, so it must be complete, readable,
+valid and free of anything that looks like a real value:
+
+- every `variable` of the stack appears in the example and nothing else does
+  (a new variable without an example fails here);
+- every assignment has a comment above it;
+- every value has the variable's declared type and the file parses with the
+  fail-closed reader (a shape it does not understand is an error);
+- the example is planned with mocked providers by a generated tofu test, which
+  runs every validation against it (the test file must be current);
+- no value looks like a secret or a real identifier: the identifier check's
+  patterns, addresses only in documentation or private ranges, no host names
+  except example.*, required placeholders that say "example", no long
+  token-like strings, no key material.
+
+The reader and the checks are exercised on broken input, so a check that stops
+biting fails here.
+"""
+
+import ipaddress
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "scripts"))
+import gen_example_tests
+import hcl_variables
+import identifier_check
+
+STACKS = ("stacks/00-foundation", "stacks/10-access")
+EXAMPLE = "terraform.tfvars.example"
+
+DOC_NETS = [
+    ipaddress.ip_network(n)
+    for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")
+]
+PRIVATE_NETS = [
+    ipaddress.ip_network(n) for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
+]
+IPV4_RE = re.compile(r"(?<![0-9.])([0-9]{1,3}(?:\.[0-9]{1,3}){3})(?![0-9])")
+HOST_RE = re.compile(
+    r"\b((?:[a-z0-9-]+\.)+(?:com|net|org|io|dev|cloud|local|lan|internal|home|corp))\b",
+    re.IGNORECASE,
+)
+HOST_OK = re.compile(r"(^|\.)example\.(com|net|org)$", re.IGNORECASE)
+LONG_TOKEN = re.compile(r"[A-Za-z0-9+/=_-]{32,}")
+# The prefixes are joined at run time so this file holds no token-shaped text.
+TOKEN_PREFIXES = re.compile(
+    "("
+    + "|".join(
+        ["dop" + "_v1_", "doo" + "_v1_", "tf" + "p_", "gh" + "p_", "gh" + "o_",
+         "github" + "_pat_", "xox[bap]-", "AK" + "IA", "AS" + "IA", "sk-[A-Za-z0-9]",
+         "-----BE" + "GIN"]
+    )
+    + ")"
+)
+# Values that are stack wiring or a documented default, not a placeholder for a
+# private or secret value, so they need not say "example".
+NEED_NOT_SAY_EXAMPLE = {
+    "region",
+    "vpc_ip_range",
+    "project_name",
+    "baseline_tag",
+    "reboot_times",
+    "reserved_ranges",
+    "resource_key",
+    "site_name",
+}
+
+
+def text_of(stack: str) -> str:
+    return (ROOT / stack / EXAMPLE).read_text(encoding="utf-8")
+
+
+def declared(stack: str) -> dict:
+    return hcl_variables.variables_in_dir(ROOT / stack)
+
+
+def type_ok(type_text: str, value) -> bool:
+    if type_text == "string":
+        return isinstance(value, str)
+    if type_text == "bool":
+        return isinstance(value, bool)
+    if type_text == "number":
+        return isinstance(value, (int, float)) and not isinstance(value, bool)
+    if type_text == "list(string)":
+        return isinstance(value, list) and all(isinstance(v, str) for v in value)
+    if type_text == "map(string)":
+        return isinstance(value, dict) and all(isinstance(v, str) for v in value.values())
+    raise AssertionError(f"the example check does not know the type {type_text}")
+
+
+def strings_in(value):
+    if isinstance(value, str):
+        yield value
+    elif isinstance(value, list):
+        for v in value:
+            yield from strings_in(v)
+    elif isinstance(value, dict):
+        for v in value.values():
+            yield from strings_in(v)
+
+
+def coverage_problems(text: str, variables: dict) -> list[str]:
+    """Disagreements between an example's text and the stack's variables."""
+    problems: list[str] = []
+    try:
+        values = hcl_variables.parse_assignments(text, EXAMPLE)
+    except hcl_variables.HclError as exc:
+        return [f"cannot read the example ({exc})"]
+    for name in sorted(set(variables) - set(values)):
+        problems.append(f"variable {name} has no entry in the example")
+    for name in sorted(set(values) - set(variables)):
+        problems.append(f"the example sets {name}, which is not a variable of the stack")
+    for name, value in values.items():
+        var = variables.get(name)
+        if var is not None and not type_ok(var.type, value):
+            problems.append(f"{name}: the value does not have the type {var.type}")
+    lines = text.splitlines()
+    for name in values:
+        index = next(
+            (i for i, line in enumerate(lines) if re.match(rf"{re.escape(name)}\s*=", line)),
+            None,
+        )
+        if index is None or index == 0 or not lines[index - 1].lstrip().startswith("#"):
+            problems.append(f"{name}: no comment on the line above it")
+    return problems
+
+
+def value_problems(text: str) -> list[str]:
+    """Anything in the example that looks like a secret or a real identifier."""
+    problems: list[str] = []
+    for number, line in enumerate(text.splitlines(), start=1):
+        for kind in identifier_check.find_kinds(line):
+            problems.append(f"line {number}: {kind}")
+        for m in IPV4_RE.finditer(line):
+            try:
+                ip = ipaddress.ip_address(m.group(1))
+            except ValueError:
+                continue
+            if not any(ip in n for n in DOC_NETS + PRIVATE_NETS):
+                problems.append(f"line {number}: an address outside the documentation and private ranges")
+        for m in HOST_RE.finditer(line):
+            host = m.group(1)
+            if not HOST_OK.search(host) and not host.endswith((".tf", ".json", ".md", ".yml")):
+                problems.append(f"line {number}: a host name that is not example.com/net/org")
+        if TOKEN_PREFIXES.search(line):
+            problems.append(f"line {number}: looks like a token or key material")
+    try:
+        values = hcl_variables.parse_assignments(text, EXAMPLE)
+    except hcl_variables.HclError as exc:
+        return problems + [f"cannot read the example ({exc})"]
+    for name, value in values.items():
+        for s in strings_in(value):
+            for m in LONG_TOKEN.finditer(s):
+                if "example" not in m.group(0).lower():
+                    problems.append(f"{name}: a long token-like string that does not say 'example'")
+        needs_example = (
+            name not in NEED_NOT_SAY_EXAMPLE
+            and isinstance(value, (str, list, dict))
+            and value not in ("", [], {})
+        )
+        if needs_example and not any("example" in s.lower() for s in strings_in(value)):
+            problems.append(f"{name}: a placeholder for a private value must say 'example'")
+    return problems
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_the_example_exists_and_covers_every_variable(stack):
+    assert coverage_problems(text_of(stack), declared(stack)) == []
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_the_example_holds_nothing_that_looks_real(stack):
+    assert value_problems(text_of(stack)) == []
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_the_example_has_a_real_number_of_entries(stack):
+    # Guards against passing because nothing was read.
+    assert len(hcl_variables.parse_assignments(text_of(stack))) >= 5
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_the_generated_example_test_is_current(stack):
+    path = ROOT / stack / gen_example_tests.TEST
+    assert path.read_text(encoding="utf-8") == gen_example_tests.render(stack, ROOT)
+    assert (
+        subprocess.run(
+            [sys.executable, "-I", str(ROOT / "scripts" / "gen_example_tests.py"), "--check"],
+            capture_output=True,
+            check=False,
+        ).returncode
+        == 0
+    )
+
+
+@pytest.mark.parametrize("stack", STACKS)
+def test_the_example_is_committable_and_a_real_tfvars_is_not(stack):
+    def ignored(name: str) -> bool:
+        result = subprocess.run(
+            ["git", "-C", str(ROOT), "check-ignore", "-q", "--no-index", f"{stack}/{name}"],
+            check=False,
+        )
+        assert result.returncode in (0, 1)
+        return result.returncode == 0
+
+    assert not ignored("terraform.tfvars.example")
+    assert ignored("terraform.tfvars")
+    assert ignored("prod.auto.tfvars.json")
+
+
+# --- the checks bite ----------------------------------------------------------
+
+GOOD = '# one\na = "x"\n# two\nb = ["y"]\n'
+VARS = {
+    "a": hcl_variables.Variable(name="a", type="string"),
+    "b": hcl_variables.Variable(name="b", type="list(string)"),
+}
+
+
+def test_the_coverage_check_accepts_a_good_example():
+    assert coverage_problems(GOOD, VARS) == []
+
+
+def test_the_coverage_check_bites_on_a_missing_entry():
+    problems = coverage_problems('# one\na = "x"\n', VARS)
+    assert any("variable b has no entry" in p for p in problems), problems
+
+
+def test_the_coverage_check_bites_on_an_unknown_entry():
+    problems = coverage_problems(GOOD + '# c\nc = 1\n', VARS)
+    assert any("c, which is not a variable" in p for p in problems), problems
+
+
+def test_the_coverage_check_bites_on_a_wrong_type():
+    problems = coverage_problems('# one\na = 1\n# two\nb = ["y"]\n', VARS)
+    assert any("a: the value does not have the type string" in p for p in problems)
+
+
+def test_the_coverage_check_bites_on_a_missing_comment():
+    problems = coverage_problems('a = "x"\n# two\nb = ["y"]\n', VARS)
+    assert any("a: no comment" in p for p in problems), problems
+    problems = coverage_problems('# one\na = "x"\n\nb = ["y"]\n', VARS)
+    assert any("b: no comment" in p for p in problems), problems
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        '# c\na = "x"\n# c\na = "y"\n',  # assigned twice
+        '# c\na = var.x\n',  # not a literal
+        '# c\na = "${x}"\n',  # template
+        '# c\na = <<EOT\nx\nEOT\n',  # heredoc
+        '# c\nresource "x" "y" {\n}\n',  # a block
+        '# c\na = "unterminated\n',
+        '# c\na = [1, 2\n',
+        '# c\na = {x = 1 y = 2}\n',
+    ],
+)
+def test_the_reader_fails_closed_on_shapes_it_does_not_understand(text):
+    assert coverage_problems(text, VARS)[0].startswith("cannot read the example")
+
+
+@pytest.mark.parametrize(
+    "line,needle",
+    [
+        ('a = "8.8.8.8"', "outside the documentation"),
+        ('a = "203.0.114.5"', "outside the documentation"),
+        ('a = "db.corp-real.com"', "host name"),
+        ('a = "account_id = ' + "2109" + '87654321"', "AWS account id"),
+        ('a = "AK' + "IA" + "Q7ZXCV" + 'BNMASDFGHJ"', "AWS access key id"),
+        ('a = "dop' + '_v1_abcdef"', "token or key material"),
+        ('a = "-----BE' + 'GIN OPENSSH PRIVATE KEY-----"', "token or key material"),
+        ('a = "tf' + 'p_abcdef"', "token or key material"),
+    ],
+)
+def test_the_value_check_bites(line, needle):
+    problems = "\n".join(value_problems(f"# c\n{line}\n"))
+    assert needle in problems, problems
+
+
+def test_the_value_check_bites_on_a_long_token_and_a_placeholder_that_is_not_one():
+    token = "A" * 20 + "b" * 20
+    problems = "\n".join(value_problems(f'# c\nadmin_ssh_public_key = "ssh-ed25519 {token}"\n'))
+    assert "long token-like string" in problems
+    problems = "\n".join(value_problems('# c\ntwingate_network = "acme"\n'))
+    assert "must say 'example'" in problems
+
+
+def test_the_value_check_accepts_documentation_and_private_ranges():
+    text = '# c\nreserved_ranges = ["192.0.2.10", "198.51.100.1", "203.0.113.9", "10.99.0.0/24", "172.20.0.0/20", "192.168.4.0/24"]\n'
+    assert value_problems(text) == []

+ 70 - 0
tests/test_unused_variables.py

@@ -0,0 +1,70 @@
+"""Every variable is used, or is on the short documented list of exceptions.
+
+tflint's terraform_unused_declarations rule runs in CI. `site_name` is declared
+before anything reads it (the telemetry stage uses it), so it carries a
+`tflint-ignore` annotation. This test keeps that list explicit: a new unused
+variable fails here instead of being quietly ignored, and an annotation on a
+variable that is used (or on one not listed) fails too.
+"""
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+ANNOTATION = "tflint-ignore: terraform_unused_declarations"
+# (directory, variable): declared on purpose, read by a later stage.
+DOCUMENTED_UNUSED = {
+    ("stacks/00-foundation", "site_name"),
+    ("stacks/10-access", "site_name"),
+}
+
+
+def directories():
+    for top in ("stacks", "modules"):
+        for path in sorted((ROOT / top).rglob("variables.tf")):
+            if ".terraform" not in path.parts:
+                yield path.parent
+
+
+def strip_comments(text: str) -> str:
+    return re.sub(r"(?m)(#|//).*$", "", text)
+
+
+def annotated(directory: Path) -> set[str]:
+    text = (directory / "variables.tf").read_text()
+    return set(
+        re.findall(rf"(?m)^# {re.escape(ANNOTATION)}\nvariable \"([A-Za-z0-9_-]+)\"", text)
+    )
+
+
+def unused(directory: Path) -> set[str]:
+    declared = re.findall(
+        r'(?m)^variable "([A-Za-z0-9_-]+)"', (directory / "variables.tf").read_text()
+    )
+    others = "\n".join(
+        strip_comments(p.read_text()) for p in directory.glob("*.tf") if p.name != "variables.tf"
+    )
+    # A variable is used when var.<name> appears in another file, or in a
+    # validation of another variable in variables.tf is not use (it is its own).
+    return {n for n in declared if not re.search(rf"\bvar\.{re.escape(n)}\b", others)}
+
+
+def test_there_are_directories_to_check():
+    assert len(list(directories())) >= 6
+
+
+def test_the_unused_variables_are_exactly_the_documented_ones():
+    found = {
+        (d.relative_to(ROOT).as_posix(), name) for d in directories() for name in unused(d)
+    }
+    assert found == DOCUMENTED_UNUSED
+
+
+def test_the_annotations_are_exactly_the_documented_ones():
+    found = {
+        (d.relative_to(ROOT).as_posix(), name) for d in directories() for name in annotated(d)
+    }
+    assert found == DOCUMENTED_UNUSED
+    for d in directories():
+        text = (d / "variables.tf").read_text()
+        assert text.count(ANNOTATION) == len(annotated(d)), d