Build a Feedback Ladder from Cheap Checks to Real Deployments
Imagine a law firm preparing a contract. A spell-checker runs first, then a grammar check, then house style rules, then a checklist of clauses that have caused disputes before. Only then does a partner with signing authority review the deal, and only then does a mock closing rehearsal happen. Each stage answers a different question. Running the expensive stages first would waste everyone's day.
Terraform review has the same shape. Static analysis reads source without contacting a provider API. Plan-aware analysis reads the JSON rendering of a saved plan, where variables, defaults, module expansion and provider schemas have been resolved. Runtime proof observes a real deployment. A check can only make a claim about the input it received. That is why terraform fmt cannot find a public bucket, and why a configuration scanner cannot prove that a bucket is private at runtime.
| Gate | Input | Proves | Cannot prove | Typical cost |
|---|---|---|---|---|
terraform fmt -check | HCL bytes | canonical layout | meaning | milliseconds |
terraform validate | configuration plus provider schemas | valid arguments, types and references | value safety | seconds |
| TFLint | HCL plus pinned rulesets | provider-specific rule violations | runtime reachability or effective IAM | seconds |
| Checkov or Trivy | source graph, sometimes plan JSON | known insecure shapes exist or not | deployed behaviour | seconds to a minute |
| OPA or Conftest | saved plan JSON | the change meets written policy | what happens after apply | seconds, plus plan time |
terraform test | configuration and disposable objects | assertions about real behaviour | full service integration | minutes |
| Integration tests | a deployed disposable environment | the service works end to end | production traffic, scale or cost | minutes to hours |
Order the gates by cost, and make each failure point at the next action. Figure 1 shows the ladder used here, including the return path that matters most: a failed gate sends the change back to the author, not forward to a later stage.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Pull request: HCL, lock file, module pins"] --> B["fmt -check
init -backend=false
validate"]
B -->|"diff or invalid"| R["Fail: fix locally and push again"]
B -->|"clean"| C["TFLint, then Checkov or Trivy"]
C -->|"finding"| R
C -->|"clean"| D["plan -out=tfplan
show -json"]
D --> E["OPA or Conftest plan policy"]
E -->|"deny or unknown"| R
E -->|"pass"| F["terraform test on disposable objects"]
F -->|"fail"| R
F -->|"pass"| G["Integration tests on a disposable account"]
G --> H["Apply the saved plan"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,D,E primary;
class B,C,F,G secondary;
class H ok;
class R danger;
Credentials mark the second boundary
Everything above the plan can run on a fork with no cloud account. The plan and everything after it need identity, network access and often money. Figure 2 draws that boundary, because most "shift left" failures come from putting a credentialed scanner in the fast lane and then disabling it when the credentials expire.
The saved plan is the pivot. If policy tests the artifact and CI applies that same artifact, what passed is what runs. A fresh plan at apply time lets a variable or data source change in between, so policy and apply can disagree; that is the normal outcome of re-planning after approval, not a theoretical race.
Lint Provider-Specific Mistakes with Pinned Rules
Validate is not lint
Validation compares configuration with the provider schema: a misspelled argument, a string where a number belongs, or a reference to a resource that does not exist. It does not know that an instance type is unavailable in the region, that a data block is unused, or that a name breaks house style. Those are lint questions.
TFLint is one optional answer. It parses HCL, loads provider schemas and evaluates rulesets. The bundled terraform ruleset covers core-language issues such as unused declarations and deprecated syntax. A provider ruleset adds resource-aware checks that only make sense with a schema in hand. TFLint is not a security scanner, and this article does not treat it as one. It is the lint rung.
Pin two things. The TFLint binary and the provider ruleset are separate releases. On 5 November 2026 the pair used here was TFLint 0.65.0 (22 October 2026) and the AWS ruleset 0.50.0 (23 October 2026). The bundled core ruleset travels with the binary, so the binary version is its pin.
Cache by both versions. The init step reads the file, resolves the exact release and installs it into the plugin directory. A cache key based only on the operating system restores yesterday's plugin after a pin bump, and the job reports success for rules it never loaded. The AWS ruleset also has a deep_check mode that calls AWS APIs. Keep it out of the pull-request lane; if you need it, use a separate read-only job with its own schedule.
Figure 3 follows the mechanics, including the branches that produce a bad lint signal: a plugin that cannot resolve, a schema that does not match the locked provider, and a finding that is real but has an approved exception.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A[".tflint.hcl: terraform preset + AWS ruleset 0.50.0"] --> B["tflint --init"]
B --> C{"Plugin and ruleset resolved?"}
C -->|"no"| C1["Fail: pin, mirror or cache is wrong"]
C -->|"yes"| D["Cache by TFLint 0.65.0 + ruleset 0.50.0"]
D --> E["tflint --format compact"]
E --> F{"Rule finding?"}
F -->|"no"| G["Lint gate passes"]
F -->|"yes"| H["Triage: schema match, real defect, exception"]
H -->|"real defect"| I["Fix the argument or resource"]
H -->|"schema mismatch"| J["Inconclusive: align ruleset with provider"]
H -->|"approved exception"| K["Narrow ignore with owner and expiry"]
H -->|"false positive"| K
I --> G
K --> G
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,D,E secondary;
class C,F,H primary;
class I,G ok;
class C1 danger;
class J,K warn;
The useful diagnostic names the rule, file and line, resource address, and the provider version the ruleset was tested against. tflint --format compact gives the first three in a form CI can annotate. The fourth belongs in the tool record, because a ruleset released before your provider upgrade may not understand a new argument and will stay silent or report a false positive.
Scan Configuration Without Treating It as Runtime Proof
A configuration scanner matches a library of known bad shapes against a graph. Checkov and Trivy are the examples here, chosen because both are actively released and both scan Terraform. On 5 November 2026 their latest releases were Checkov 3.4.3 (2 November 2026) and Trivy 0.76.2 (5 November 2026). These are observations for a pin, not endorsements. Re-check the release pages before copying the numbers into a pipeline.
tfsec needs a more careful status note. Its last release was 1.28.14 on 2 May 2025. The repository is not archived, and the binary still installs and runs. But its README says the project has been consolidated into Trivy and that engineering attention is directed there. Treat tfsec as legacy: reasonable to keep an existing gate running while you migrate, unreasonable to start a new gate on it without a named maintainer and a migration date. "Not archived" is not the same as "actively maintained".
Two scanners, different inputs. Their policy IDs and scan surfaces differ in ways that matter at the gate:
| Tool | Input | Strengths | Watch |
|---|---|---|---|
| Checkov | HCL source, or plan JSON through its terraform_plan framework | stable IDs such as CKV_AWS_24 (open SSH), CKV_AWS_20 (public-read ACL) and CKV_AWS_17 (public RDS) | Python-based; plan input sees evaluated values, source input does not |
| Trivy | HCL source, images, filesystems and secrets | one binary for a pipeline that also builds images | the configuration scanner reads source, not plan values |
What a scanner proves is narrow: the configuration contains, or does not contain, a shape its rules recognise. It cannot prove runtime behaviour. A security group open to 0.0.0.0/0 may be unreachable behind a network ACL or route table. An IAM wildcard may be constrained by a permissions boundary or SCP, or may be worse than the severity suggests. An encryption attribute may exist while the KMS key policy denies the service principal. A public bucket ACL may be overridden by a bucket policy Terraform does not manage.
Provider defaults cut both ways. A scanner reading source sees what you wrote, not what the provider does with an omitted argument. Some resources encrypt by default in current provider versions; a rule demanding an explicit encryption block flags a configuration that is already encrypted. Scan the plan when evaluated values matter, and still call the result a statement about the proposed change, not about the account.
Tool lifecycle is part of the pin. Record the owner, release cadence, last release date, security policy, licence, and the provider versions the rules were tested against. Prefer a signed release or an image digest over a floating tag. A scanner is code with privileges over your repository and, sometimes, over your plan artifact; it deserves the same supply-chain care as a provider binary.
Evaluate a Saved Plan with OPA or Conftest
Read the change, not the snapshot
A saved plan is Terraform's proposal in a binary format. Its documented JSON rendering also carries the format and engine versions, variables, planned values, output changes, prior state and completion metadata. Policy needs the action, the values after the change, and the markers for values still unknown at plan time, all of which sit under resource_changes. The planned-values section alone loses both the action and the unknown information.
Conftest wraps the Open Policy Agent runtime. It evaluates Rego against JSON documents. The rule below denies a create of an ingress security-group rule whose port range covers 22 and whose CIDR blocks contain 0.0.0.0/0; its message names the resource address so the developer does not have to search the plan.
Unknown is not safe
A value Terraform cannot know until apply, such as a generated ID or ARN, appears under after_unknown rather than as a value. A naive rule that iterates the CIDR list finds nothing, produces no denial, and the gate reports a pass. Absence of evidence becomes evidence of safety. The policy must detect an unknown security-relevant attribute and return a distinct denial or warning that says "unknown at plan time".
Schemas drift, and so do shapes. Provider schemas change between major versions, optional blocks are omitted, and nested blocks may be sets rather than objects. A rule written for the inline ingress block of aws_security_group will not see a separate aws_security_group_rule, and the newer aws_vpc_security_group_ingress_rule uses cidr_ipv4 instead of cidr_blocks. Port ranges and the all-ports encodings need more than one equality check. Use object.get with an explicit default, decide whether that default is safe for the pinned provider version, and unit-test the policy against known, unknown and absent values. A policy that silently skips a shape it does not recognise is an inconclusive check wearing a green badge.
Confidentiality is the third hazard. Plan JSON can contain variable values, output values, passwords, tokens and private keys in clear text. sensitive_values is a display hint, not encryption; it marks paths so the CLI can redact them while the values remain in the document. State has the same property. Never echo the plan to CI logs, attach it to a pull request, or upload it to an artifact store with broad access. If a downstream system needs evidence, send the policy result and resource addresses, not the plan.
Two patterns work. Keep the plan inside the job, run Conftest there, and publish only the verdict; or extract a minimal projection with a jq filter, dropping variables, output changes and prior state, and store it with short retention. Test that the projection still contains the unknown markers, or the sanitised input will be less truthful than the original. In HCP Terraform, policy evaluation can run server-side against the plan before apply, keeping the artifact inside the platform; the distinction between plan-time policy and runtime proof still applies (HCP policy overview).
The widget below is the full local pipeline: pinned tool checks, source-only gates, a saved plan, a policy that handles the unknown case, and cleanup. It assumes .tflint.hcl from the previous section and writes the policy inline. Nothing in it prints plan content.
The script is split by comments rather than jobs. In a real pipeline the static lane runs on the pull request with no secrets, and the plan lane runs in an environment-scoped job with a short-lived token. Restrictive file permissions and the cleanup trap reduce accidental exposure but do not replace artifact access control. The projection drops variables, output changes and prior state while keeping the resource changes and their unknown markers; it is still sensitive, because resource values can contain secrets. The Rego uses a safe lookup so a missing attribute does not crash the policy, and its second rule turns an unknown SSH CIDR into a refusal rather than a pass.
Exceptions Need an Owner, Reason and Expiry
Every gate eventually meets a finding that is real but temporarily acceptable: a public load balancer for a marketing site, a bastion in an isolated sandbox, an unencrypted legacy bucket scheduled for migration. The wrong response is to lower the gate for everyone. The durable response is a narrow, time-bounded exception with a team accountable for it.
An exception record needs six fields. The rule identifies exactly what is waived, not the whole scanner. The resource address identifies exactly where, so a new resource of the same type is still checked. The owner is a team or role with authority to accept the risk, not an individual who may change jobs. The reason states the constraint clearly enough that a reviewer can disagree. The expiry is a date, not "until fixed". The compensating control says what reduces the risk while the exception is open.
| Field | Example | Why it matters |
|---|---|---|
| Rule | CKV_AWS_24 | A scanner-wide skip hides unrelated findings |
| Resource | aws_security_group_rule.bastion_ssh | A type-wide skip hides every future rule of that type |
| Owner | platform-security team | An individual leaves; a team keeps accountability |
| Reason | "Sandbox bastion, SSM cutover in INFRA-412" | Forces a reviewer to see the actual risk |
| Expiry | 2026-12-15 | Creates a decision, not a permanent hole |
| Control | "Single instance, Elastic IP allowlist, session logging" | Shows why the residual risk is bounded |
Tool-native suppressions work only when they carry the same information. Checkov accepts # checkov:skip=CKV_AWS_24:<reason> immediately above the resource; TFLint accepts # tflint-ignore: <rule> with an optional reason. Both are visible in review, which is an advantage, and easy to copy without an expiry, which is the disadvantage. Pair each inline suppression with a central record that CI validates. The comment explains the local decision; the record makes it searchable and expirable.
Enforce expiry mechanically. A policy job reads exceptions.yaml, checks the six fields, confirms the owner exists in the owning group, and requires expires to be in the future. An expired entry fails the pipeline with the rule, resource and owner in the message. Do not rely on a calendar reminder; the person who set it may be the person who left. A grace period is fine if it is explicit and itself expires.
Diagnostics decide whether the gate is respected. A useful failure gives the rule ID and title, file and line, resource address, one sentence on why the shape is risky, the smallest fix, the exception path and owner, and a documentation link. A useless failure dumps two hundred findings marked "HIGH" with no ordering. Group duplicates before reporting: four S3 public-access-block findings for one bucket are one decision, not four. Sort by resource and rule, collapse repeated rule text, and keep the machine-readable report as an artifact for the security team rather than the developer's console.
Figure 4 shows the triage path. The important branch is the middle one: an exception is an explicit, expiring decision, not a fourth kind of pass. The lower branch is the one teams forget: when evidence is inconclusive, the gate must say so, because a green result built on missing data is worse than a red one.
An exception without a date is a policy change
The expiry loop is the difference between risk management and risk deferral. An exception with a date, owner and compensating control is a decision that can be reviewed, renewed with new evidence, or closed. One without a date is a permanent hole with extra steps.
Reject a Concrete Misconfiguration and Keep the Signal Useful
One deliberately insecure rule tests every rung. An AWS security-group rule that allows SSH from the entire internet is a good teaching case: validation accepts it, TFLint says nothing about the CIDR, Checkov flags it by policy ID, and a plan policy can flag it with full resource context. The same change produces four different levels of evidence, which is exactly what the ladder is for.
Lab status: design-only. The commands are the acceptance test, not a transcript of an executed cloud run. No AWS resources are created and no real credentials are needed; the provider uses validation skips and placeholder credentials so the plan stays local. The card carries the setup, gate order, expected evidence and cleanup.
Add a meaningful CI gate
Goal: make one insecure configuration fail for the right reason, then prove that an approved exception and an inconclusive result take different paths.
Prerequisites: Terraform 1.17.1, AWS provider 6.72.0, TFLint 0.65.0 with AWS ruleset 0.50.0, Checkov 3.4.3, Conftest 0.71.1, verified on 5 November 2026. Use a local backend; no AWS account or real secret is required.
Setup. Give the provider placeholder credentials with the four validation skips enabled:
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
skip_region_validation = true
}
Declare aws_security_group_rule.ssh_from_world on port 22 with cidr_blocks = ["0.0.0.0/0"] and a literal security group ID.
Steps:
- Write
versions.tfandmain.tfwithaws_security_group_rule.ssh_from_worldopen to0.0.0.0/0on port 22. Runterraform init -input=falseandterraform validate; record that both succeed. - Run
tflint --initandtflint --format compact. Record that the lint gate does not treat this as a security finding. - Run
checkov -d . --framework terraform --compact --quiet --check CKV_AWS_24. Save the exact failure: rule ID, resource address, file and line. - Create
tfplan,plan.jsonand thepolicy-input.jsonprojection, then runconftest test --policy policy policy-input.jsonwith the two-rule policy from the code widget. Record the denial. - Change the CIDR to
203.0.113.0/24, re-plan, and re-run both scanners. Confirm both pass. - Restore the open CIDR and add a scoped skip plus a central entry with owner
platform-security, reasonsandbox bastion, INFRA-412, controlsingle instance and session logging, and expiry2026-12-15. Run the validator with that date and with a past date. The first passes with a visible exception; the second fails. - Replace the CIDR with an input variable that has no default. Re-plan and run Conftest. Confirm the unknown-value rule denies instead of passing.
Expected observation: validate proves syntax, TFLint stays silent on the security question, Checkov reports CKV_AWS_24, and Conftest reports the same resource from the plan. Fixing the CIDR clears both. An exception clears the gate but stays visible. An unknown CIDR is refused, not waived.
Failure check: a green Checkov run on step 3 usually means the wrong framework or a path outside the scan root. A green Conftest run on step 7 means the policy iterates after without checking after_unknown. A validator that accepts a past expiry is comparing strings or ignoring time zones.
Cost dimensions: no cloud spend and no apply; provider download, runner minutes, and triage time.
Cleanup: delete the plan artifact, its JSON projection and the working directory. If you adapted this to a real account, run terraform destroy, then verify the rule and group are gone.
Next in the Series
In Integration Tests, Terratest and Real Service Readiness, we'll explore Exercise the cloud behavior that mocks and plan assertions cannot prove.