Infrastructure testing and policy
Test what you actually know
Infrastructure testing is the process of checking whether infrastructure definitions, intended changes and deployed behavior meet a contract. Policy-as-code represents rules in a machine-evaluable form. Neither means a valid template will create a healthy or secure service. A useful test names its input, expected result and the boundary of its evidence.
Imagine Northwind Books operates a private order database. A change to increase storage must not make it public, disable encryption or replace its persistent data unexpectedly. First inspect the planned action, then test the policy and verify service behavior in an approved environment. This chapter uses synthetic records, not real provider plans. Prerequisites: safe deployments, policy exceptions and safe cloud API automation.
Build an evidence ladder
| Layer | Example assertion | What a pass does not prove |
|---|---|---|
| Schema and syntax | Required field is present and has the correct type | Credentials, capacity or correct architecture |
| Lint | Naming, maintainability and forbidden patterns | Runtime behavior or full policy coverage |
| Unit or module test | A module derives the expected subnet list | Real network routes or permissions |
| Plan policy | No unapproved public storage or destructive DB change | Actual deployed configuration |
| Integration | A disposable environment accepts authorized traffic | Production-scale availability |
| Smoke and negative tests | App reads a synthetic record; unauthorized reader denied | All business behavior or all attack paths |
| Recovery | Restore data and measure usable service recovery | Every future incident scenario |
A unit test should be small and deterministic. An integration test exercises components together, including actual provider semantics where authorized. A smoke test checks a small critical path quickly after deployment. A negative test demonstrates an expected rejection; an error from a broken client is not evidence that the intended access control rejected it. Record the test identity and reason. A recovery test must verify restored data and service usability, not just snapshot existence. These layers complement one another. A skipped mandatory gate is unknown, not pass.
Use provider and tool capabilities at the right boundary
Official documentation excerpts reviewed on November 28, 2026 inform this comparison. Verify exact tool versions, provider versions and feature eligibility before use.
| Tool or provider | Preview or test | Enforcement caveat |
|---|---|---|
| Terraform | terraform validate checks configuration consistency; terraform test supports plan/apply tests and provider mocks from v1.7 | Validation does not query remote service correctness. Apply tests with real providers can create billable resources. Mocking does not prove API semantics. |
| AWS | CloudFormation change sets preview changes; CloudFormation Guard checks structured data against rules | Guard run in CI is advisory unless failure blocks release; appropriate Hooks can enforce supported operations. |
| Azure | ARM/Bicep what-if predicts changes | Azure Policy effects such as audit and deny differ. Applicability, scope and supported resource properties matter. |
| Google Cloud | Infrastructure Manager previews Terraform deployments | Organization Policy constraints act at supported hierarchy scopes; preview is not proof of enforcement. |
| OPA | Rego evaluates structured inputs; opa test checks policy behavior | The calling pipeline or admission layer must reject disallowed or unavailable decisions. |
Preview can contain unknown or incomplete values. Terraform's plan action list may represent replacement as delete/create or create/delete; review both orders and the after_unknown information, not just counts of creates. Translate provider-specific input through a versioned, tested adapter; never feed a different schema into the policy and assume it works. Plan and validation operations can load executable plugins or modules, and preview workflows may contact APIs. This offline lab runs none of those tools. See Terraform validate, Terraform tests, CloudFormation Guard, Azure what-if, Azure Policy effects, Infrastructure Manager preview and Organization Policy.
A policy rule is not an enforcement mechanism
OPA (Open Policy Agent) evaluates Rego policies over JSON-like data. This illustrative OPA v1.x snippet checks only one property of a normalized change. It is not a complete Terraform policy. The calling system must validate the shape and knownness of every input before evaluation, reject an undefined decision or evaluation error, and enforce the outcome. The static Rego snippet and tests are not executed in this package; the Python fixture below is independently tested, not a Rego interpreter.
package bytemind.release
import rego.v1
deny contains "public access" if { some change in input.changes change.action != "delete" change.public == true}A valid input containing an update with public: true should produce the denial string; a private update should not produce that finding. Missing public could result in no matching rule, so validate the input separately. A complementary test module would assert the expected denial set with with input as ... for valid cases. Use opa test in a separately approved isolated environment. Check rule revisions, allow/deny precedence, resource scope and exceptions. Never interpret absence of a deny rule as approval for malformed or unreviewed inputs. OPA policy testing.
An exception is not a comment saying ignore. It needs a named rule, narrow resource scope, expiry, accountable approver, justification and compensating controls. Absolute denies cannot be overridden by an ordinary exception. Test expiry and wrong-scope cases. In this lesson the stateful destructive change and public access rules are hard stops, so no exception path is implemented.
Run a local mock plan policy
The following Python 3 standard-library example accepts a deliberately small, normalized dictionary. public, encrypted and stateful are boolean evidence flags supplied by the fixture; None represents unknown and blocks review. A delete has no desired public/encryption state, but the toy schema still requires known flags and checks the stateful property. A real adapter needs to derive statefulness from the existing and proposed resource, not from an untrusted author-supplied label. This function returns findings only. An empty list means no finding in these rules, not authorization.
def findings(plan): # Strict contract for this small teaching schema only. if not isinstance(plan, dict) or set(plan) != {"changes"}: return ["invalid plan"] changes = plan["changes"] if not isinstance(changes, list): return ["invalid changes"] issues, seen = [], set() for c in changes: required = {"id", "action", "public", "encrypted", "stateful"} if not isinstance(c, dict) or set(c) != required: issues.append("invalid change") continue name = c["id"] if not isinstance(name, str) or not name or name in seen: issues.append("invalid or duplicate id") continue seen.add(name) if c["action"] not in ("create", "update", "delete", "replace", "no-op"): issues.append(name + ": unknown action") continue if any(c[k] is not True and c[k] is not False for k in ("public", "encrypted", "stateful")): issues.append(name + ": unknown policy evidence") continue if c["stateful"] and c["action"] in ("delete", "replace"): issues.append(name + ": destructive stateful change") if c["action"] != "delete": if c["public"]: issues.append(name + ": public access") if not c["encrypted"]: issues.append(name + ": encryption required") return sorted(issues)
safe = {"id": "orders-db", "action": "update", "public": False, "encrypted": True, "stateful": True}print(findings({"changes": [safe]}))print(findings({"changes": [dict(safe, action="replace", public=True)]}))print(findings({"changes": [dict(safe, encrypted=None)]}))Expected output:
[]['orders-db: destructive stateful change', 'orders-db: public access']['orders-db: unknown policy evidence']The first update passes the narrow checks. The second contains two separate blockers; replacement may destroy old data even if a new instance is created first. The third is held for evidence, not silently treated as encrypted. Try an empty plan, duplicate IDs, an unknown action or a missing key. A clean empty plan can mean no planned changes; it is not evidence that deployed resources are healthy. The normalizer and release controller must independently establish completeness and trusted inputs.
Protect plan artifacts and extend coverage
Terraform saved plans and machine-readable state/plan output can contain sensitive values even when a human-readable display redacts them. Never publish raw state, plan JSON or output to public CI logs or attach it to unrestricted tickets. Generate a minimal allowlisted summary in a trusted process; avoid regex-only redaction. Restrict access, retention, encryption and audit for originals. Do not copy secret-bearing values into findings; this toy model contains only fictional IDs and flags. See Terraform show and plan JSON format.
Practice: run the code, test a public update, encrypted stateless delete, duplicate identity and malformed plan. Write one positive and one negative test for actual authorization and a restore drill acceptance condition. Label which tests require real provider access and which can run offline. The next lesson ties a reviewed plan to a release and verifies what happens afterward.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Infrastructure testing and policy — knowledge check
Choose the best answer for each offline scenario.
A Terraform configuration passes validate. What remains unproven?
What does a provider mock test establish?
A normalized stateful database action is replace. What does the local policy return?
Why must the caller validate a Rego input before evaluation?
What is safe to publish in ordinary CI logs?