Skip to content
intermediate Phase 11 · Policy Enforcement, Security Scanning, and Secrets

Static Security Scanning

Running tfsec, Checkov, and Trivy against configurations before apply.

55m
0 problems
Topic Progress 0%

Catch risky infrastructure patterns before cloud credentials are needed

Static scanning reviews configuration without creating resources

A static infrastructure scanner parses Terraform configuration and checks it against rules about security, reliability, and configuration practices. It can flag a public storage bucket, an unencrypted disk, a security group open to the internet, or an identity policy with broad permissions before an apply reaches a cloud API. Tools such as Checkov, Trivy configuration scanning, and tfsec-style scanners provide rule sets and CI integrations. They complement terraform fmt and validate: formatting checks style, validation checks configuration structure, and security scanning evaluates risky patterns.

Static scanning is useful early because it often needs no cloud credentials. A pull request can be checked from source files, which limits the privileges required for untrusted branch code. The scan can run alongside formatting and validation before a plan. When the scanner supports plan input, a second stage can inspect the resolved resource graph and values that are not obvious from an individual module. Plan scanning is still not a runtime assessment; it does not verify that a cloud service is currently reachable or that every provider default behaves as expected.

A finding needs context. A public network rule might be intentional for a public web load balancer but dangerous for a database subnet. The author should identify the resource, the condition that triggered the rule, the exposure, and the control that reduces it. A scanner cannot always infer the application's trust boundary or whether a resource is internet-facing by design. Treat a finding as a review signal, then verify the deployed architecture and requirement.

Rule identifiers and severity labels are not perfectly comparable across tools. One tool may classify a missing encryption setting as high severity while another marks the same pattern medium. Establish a team policy that maps severity to action. For example, critical exposure can block a merge, high findings require remediation or security approval, and low findings can be tracked. Keep the policy stable and explain how new rules enter the gate so a tool upgrade does not unexpectedly block every branch.

Run scans on pull requests and on the default branch. The pull request gate catches new problems before merge; scheduled scans find drift in policy, scanner rules, or files that are not changed often. Pin scanner versions or otherwise control updates so a rule change is reviewable. Store machine-readable output as a CI artifact with restricted access if it includes account names or architecture details. Avoid dumping environment variables or credentials into logs.

A baseline can help introduce scanning to a mature repository that already contains many findings. The baseline records accepted findings so the gate focuses on new violations. Review the baseline, assign owners, and set an expiration or reduction plan. A baseline is not a remediation: old public exposure remains risky even when it no longer fails the pipeline. Prefer narrow suppressions with a written reason and an issue or owner reference. Do not suppress a whole rule globally because one resource has a valid exception.

Static scanners can also identify policy conventions such as required tags, approved regions, or encryption configuration. Keep security invariants separate from stylistic preferences. A noisy gate that blocks harmless patterns trains developers to bypass it. Measure false positives and tune rules with security owners while preserving controls that protect data and identity.

In an interview, describe the difference between scanning HCL, scanning a plan, and assessing a running account. Explain why a no-credential source scan is a useful early gate, then discuss how you review exceptions without turning them into permanent blind spots. This demonstrates an understanding of both tool behavior and secure delivery.

A scanner's source analysis can miss values supplied through variables, modules, or provider behavior. It may see a variable rather than the final CIDR or fail to reason about a dynamically selected setting. A plan-aware rule can resolve some of that context, but it still reflects planned configuration rather than live traffic. Combine code scanning with plan policy, cloud configuration monitoring, and runtime controls where the risk requires them.

Make findings actionable in the pull request workflow

A useful gate tells the author what changed and how to fix it

Put the scan result near the infrastructure diff. A concise CI summary should include the rule ID, severity, affected file and resource, a short explanation, and a link to remediation guidance. Developers should be able to reproduce the scan locally with the same scanner version and configuration. If local and CI versions differ, the result may be difficult to debug. Treat scanner configuration as code and review changes to skipped rules or severity thresholds.

On a pull request, compare findings with the target branch or an approved baseline. Failing on every historical result can make adoption impossible; failing only on newly introduced critical or high findings gives a path to improve. Still publish the full result so maintainers can see old exposure. Do not use an unstable line number as the only finding identity because formatting changes can move it. Resource address and rule ID are often more durable, though refactors can still alter addresses.

A suppression should be local and auditable. Put a reason beside the resource or in a policy exception file, link a ticket, name the owner, and set a review date for temporary exceptions. The justification should explain why the risk is acceptable and which compensating control exists. ?False positive? is not enough without evidence. If the scanner cannot understand a custom module, add a test or a policy assertion that demonstrates the intended control rather than suppressing every finding for that module.

Separate source scanning from authenticated plan and cloud scans. Pull request code can be supplied by contributors, so do not expose production credentials to arbitrary branch workflows. Run untrusted-code scans in an isolated job with no secrets. A protected workflow can create a plan using limited read permissions or trusted credentials after approval. If plan files are passed between jobs, protect the artifact because planned values may include sensitive data. Cost and policy tooling should consume the same reviewed plan revision.

When a rule blocks a merge, the remediation should preserve the service requirement. A public endpoint might need ingress on HTTPS while still restricting administration to a trusted network. An encryption finding may require a provider attribute and a migration plan for existing data. A broad IAM finding may be addressed by narrowing actions and resource ARNs. Do not add a default value just to make the scanner green if it creates a production outage or silently changes existing resources.

Scanner updates can add new checks or change how resources are interpreted. Pin versions, review release notes, and test upgrades on a representative repository before changing the required gate. Run the new version in report-only mode first if the existing baseline is large. Then triage newly discovered high-severity cases and update the baseline intentionally. Keep the scanner output from the previous and new version for comparison during the rollout.

For a reliable pipeline, format and validate first, then run source scanning, then build a plan and run plan policies when credentials and trust boundaries allow. Require the security status check before merge. Keep apply behind protected branches and approval gates. A clean source scan does not authorize apply; it means only that the configured static rules found no blocking issue in the scanned inputs.

Check the gate itself with a small fixture or test configuration that deliberately contains a known insecure pattern. Confirm the scanner reports it and that the CI step fails according to policy. Also test a justified exception and verify that it appears in output. Without a negative test, a misconfigured command that scans zero files can look like a green security result.

The pull request author should receive an actionable failure, not only a generic ?scan failed.? Preserve the report even when the process exits nonzero. Distinguish scanner execution errors from policy violations: missing binary, invalid config, and timeout should fail with a clear infrastructure error rather than being reported as a security pass. This makes the required check trustworthy.

Balance scanner coverage, false positives, and security ownership

Static scanning is one layer in the control system

Static analysis is fast and repeatable, but it has a bounded view. It inspects source or a plan and cannot prove that a deployed cloud account has no manual changes, that a network rule is reachable through every path, or that credentials are handled safely at runtime. A passing scan means the selected rules passed on the selected inputs. It does not mean the system is secure. Pair static checks with plan policy, cloud posture or drift detection, identity reviews, and runtime monitoring according to the threat model.

Some risks are best enforced as policy rather than scanner warnings. A policy can require encryption, restrict regions, or block a public database in every workspace. A scanner is useful for surfacing likely defects and giving developers quick feedback. The boundary depends on the organization: critical invariants should have an authoritative enforcement point, while advisory checks can help teams discover risks earlier. Avoid duplicating dozens of contradictory rules across tools unless ownership and precedence are clear.

False positives are a practical cost. If developers encounter many irrelevant warnings, they may ignore real exposure or blanket-suppress a rule. Track the rate of findings accepted as false positives and review patterns. Improve module interfaces so safe defaults are explicit; then scanners can reason about those settings more accurately. When a rule needs domain context, encode that context in a custom policy or a narrow exception rather than asking reviewers to remember an undocumented convention.

A baseline is useful during rollout but can hide security debt. Add owners and dates, report baseline counts, and make new findings visible. Prioritize findings by exploitability and impact, not only by the tool's severity label. A publicly exposed database with sensitive data requires urgent action; a low-risk development bucket may have a different response. Security teams should help prioritize rather than treating all scanner output as equally dangerous.

The tool choice should fit the codebase and workflow. Evaluate supported Terraform syntax, module handling, plan input, policy customization, output formats, update cadence, and developer experience. Compare results on representative repositories before selecting a required gate. Check whether the tool follows modules into local or remote source and whether it can evaluate rendered plan values. Do not choose based only on a long rule count; coverage quality and actionable remediation matter more.

Security exceptions need governance without blocking every legitimate design. An approved public service can still have a valid exposure, but its exception should identify the intended listener, authentication, network protections, and owner. A temporary exception should expire. A permanent exception should be revisited when the architecture changes. Preserve the original finding and approval record so auditors can distinguish a deliberate exception from a disabled scanner.

In an interview, explain a layered workflow: no-credential source scan on every pull request, plan-aware policy after a trusted plan exists, protected apply, and periodic cloud drift checks. Mention how you handle preexisting findings, version upgrades, and scoped exceptions. This shows you understand that a tool provides one control rather than a universal security guarantee.

Use Sensitive Values and Redaction to understand why CI logs and plan artifacts need protection, and OPA and Conftest Policy Gates for rules that must block a proposed plan. Static scanning is strongest when each control has a clear owner and the pipeline explains which inputs were actually inspected.

Quiz

1. What does a source-level Terraform scanner typically do?

Question 1 options

2. Why maintain a baseline when enabling scanning in a mature repository?

Question 2 options

3. What should a security suppression include?

Question 3 options

4. What does a clean static scan establish?

Question 4 options

Flashcards

Question

What is static Terraform scanning?

Answer

Analyzing HCL or plan data for risky infrastructure patterns before apply.

Question

Why scan pull requests without cloud credentials?

Answer

It gives early feedback while reducing the risk of exposing privileged credentials to untrusted code.

Question

What is a security scan baseline for?

Answer

Separating existing findings from new ones during adoption while keeping old debt visible.

Question

What makes a suppression auditable?

Answer

A narrow scope, written reason, owner or ticket, and an expiration or review date where appropriate.

Question

Does a passing source scan prove the cloud is secure?

Answer

No. It only means selected rules passed for the scanned source or plan input.

Revision Notes

Key Takeaways

  • 1. Source scanners catch risky configuration patterns early and complement validation, plan checks, and runtime controls.
  • 2. Run untrusted pull request scans without production credentials and protect plan artifacts separately.
  • 3. Use reviewed baselines to focus new findings without hiding existing security debt.
  • 4. Keep suppressions narrow, justified, owned, and time-bound when possible.
  • 5. A passing scan applies only to selected rules and inputs; it is not a proof of overall security.

Interview Tips

  • • Distinguish source scanning from plan policy and live cloud posture assessment.
  • • Explain how you introduce a baseline while keeping historical findings visible.
  • • Describe how a justified exception is documented and reviewed.
  • • Mention a negative test that proves the CI gate detects an intentionally insecure fixture.

Cheat Sheet

Static Security Scanning Cheat Sheet

Phase: Policy Enforcement, Security Scanning, and Secrets | Level: intermediate

Key points:

  • Static scanners parse HCL and flag patterns like public buckets or unencrypted disks.
  • Baseline files record accepted findings so teams only review newly introduced issues.
  • Scanning runs on pull requests because it needs no cloud credentials or plan output.
  • Suppressions should carry a written justification next to the ignored check identifier.

Tags: terraform, security, scanning

Continue Learning

Before You Start

  • No prerequisites listed.

Related Reading