IaC Security: Scan with tfsec, Checkov, Terrascan

Khimananda Oli 7 min read Virtualization
IaC Security: Scan with tfsec, Checkov, Terrascan

By Khimananda Oli | Last reviewed: August 2026

Misconfigured infrastructure remains the leading cause of cloud breaches, yet most teams still treat IaC security as an afterthought during deployment rather than a shift-left validation step. Effective IaC security: scan with tfsec, Checkov, Terrascan integrates static analysis directly into your development workflow to catch exposed ports, missing encryption, and overly permissive IAM roles before you ever run terraform apply. This guide provides the exact configuration patterns and CI integration steps needed to enforce policy-as-code without slowing down delivery.

How do you implement IaC security scanning in CI pipelines?

Implementing IaC security: scan with tfsec, Checkov, Terrascan requires more than installing binaries; it demands strategic placement within your DevSecOps shift-left strategy. In practice, I recommend a tiered approach where lightweight checks run locally via pre-commit hooks, while comprehensive scans execute in CI on every pull request. This prevents noise fatigue while ensuring no insecure code merges to main.

Developer CommitTerraform / HCLtfsec (Fast)Local + CI GateCheckov (Broad)Compliance PoliciesTerrascan (Deep)Remediation DataAggregated ReportSARIF / JSON OutputMerge / BlockPolicy Enforcement
IaC security scanning pipeline integrating tfsec, Checkov, and Terrascan for layered defense

The key to sustainable adoption is treating scanner output as structured data, not just terminal noise. Configure each tool to emit SARIF or JSON so your CI platform can annotate pull requests directly. When developers see "S3 bucket missing versioning" inline on line 42 of their diff, fix rates increase dramatically compared to burying findings in a separate dashboard. For teams managing sensitive data, pair these scanners with proper secrets handling to ensure credentials never leak during the scan process itself.

Pre-commit hook configuration

Catch issues before they enter version control using pre-commit. This reduces CI cycle time and gives immediate feedback:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/aquasecurity/tfsec-pre-commit
    rev: v1.28.4
    hooks:
      - id: tfsec
        args: ["--soft-fail", "--format=json"]
  - repo: https://github.com/bridgecrewio/checkov
    rev: 3.2.35
    hooks:
      - id: checkov
        args: ["--quiet", "--compact"]
  - repo: https://github.com/tenable/terrascan
    rev: v1.19.9
    hooks:
      - id: terrascan
        args: ["scan", "-t", "aws", "--non-recursive"]

What are the key differences between tfsec, Checkov, and Terrascan?

Choosing the right tool depends on your specific compliance requirements, supported frameworks, and performance constraints. While there is overlap, each scanner has distinct strengths that make them complementary rather than redundant when implementing IaC security: scan with tfsec, Checkov, Terrascan.

FeaturetfsecCheckovTerrascan
Primary FocusTerraform/HCL security best practicesMulti-framework compliance (CIS, NIST, SOC2)Detailed vulnerability & misconfiguration DB
Supported LanguagesTerraform, CloudFormation, Bicep, ARMTerraform, CFN, K8s, Docker, Helm, ServerlessTerraform, CFN, K8s, Helm, Docker
Scan SpeedVery Fast (Go binary, parallel)Moderate (Python-based)Moderate (Go binary, large DB load)
Custom PoliciesRego (OPA) or native GoPython or YAML (easier entry)Rego (OPA)
Remediation GuidanceBrief links to docsLinks to Bridgecrew/Cortex docsDetailed fix snippets + severity context
CI IntegrationSARIF, GitHub Actions nativeSARIF, JUnit, native integrationsSARIF, JSON, HTML reports
Best ForFast PR gates, Terraform-heavy shopsAudit/compliance evidence, polyglot IaCDeep forensics, regulated environments

In my experience helping Nepal-based fintechs achieve ISO 27001 compliance, Checkov's extensive built-in policy library (800+ checks) satisfies auditors fastest. However, for daily developer workflows on pure Terraform projects, tfsec's speed and low false-positive rate make it the superior first-line defense. Terrascan fills gaps with its curated vulnerability database, particularly useful when you need to explain why a finding matters to non-technical stakeholders.

How do you configure custom policies for organizational standards?

Built-in rules cover generic cloud security, but every organization has unique constraints—specific tagging schemas, approved instance types, or region restrictions. Writing custom policies enforces these standards automatically. Below is a practical Rego example for tfsec that blocks any AWS S3 bucket lacking mandatory cost-allocation tags:

# custom_policies/s3_tags.rego
package custom.s3.tags

import data.aws.s3.bucket

deny[res] {
    bucket := input.resource_changes[_]
    bucket.type == "aws_s3_bucket"
    not bucket.change.after.tags["CostCenter"]
    res := {
        "msg": sprintf("S3 bucket '%s' missing required CostCenter tag", [bucket.address]),
        "severity": "HIGH",
        "resource": bucket.address
    }
}
IaC Source Filesmain.tf / variables.tfPlan JSON OutputPolicy Engine (OPA)Built-in Rules (CIS/NIST)Custom Org PoliciesException AllowlistsPASS ResultsCompliant ResourcesFAIL ResultsViolations + RemediationCI DecisionBlock / WarnComment on PR
Custom policy evaluation architecture combining built-in compliance rules with organizational standards

For Checkov, custom Python policies offer lower barrier to entry for teams already comfortable with Python. Store custom policies in a shared repository and reference them via --external-checks-dir in CI. This centralizes governance while allowing individual teams to opt into stricter controls. Remember to version your policy repository independently from application code; policy changes should follow their own review cycle, especially when preparing for audits like SOC 2 evidence automation.

How do you reduce false positives and manage exceptions?

Scanner fatigue kills adoption faster than any technical limitation. A common mistake is enabling all rules at HIGH severity immediately. Instead, baseline your existing codebase first, then ratchet up enforcement. All three tools support inline suppression comments for legitimate exceptions, but use them sparingly and always require justification:

  • tfsec: # tfsec:ignore:aws-s3-enable-bucket-encryption with mandatory explanation comment on next line
  • Checkov: # checkov:skip=CKV_AWS_19:Legacy app requires public read until migration Q3
  • Terrascan: Use .terrascan.toml skip-rules list with ticket references for audit trails

Create an exception review process. Monthly, export all suppressed findings and validate they're still valid. Stale exceptions become security debt. In regulated environments, maintain an exception register mapping each suppression to a risk acceptance form signed by the system owner. This discipline separates mature IaC security: scan with tfsec, Checkov, Terrascan implementations from checkbox exercises.

Which scanner should you prioritize for Kubernetes and multi-cloud?

If your stack extends beyond Terraform/AWS, tool selection shifts. Checkov leads for Kubernetes manifest scanning with native Helm chart support and pod security standard checks. Terrascan excels at detecting container image vulnerabilities referenced in IaC. For teams adopting Kubernetes security best practices, run Checkov against both Terraform modules generating K8s manifests AND the rendered YAML output to catch drift between intent and artifact.

Scanner Coverage by PlatformPlatformtfsecCheckovTerrascanAWS★★★★★★★★★★★★★★☆Azure★★★☆☆★★★★★★★★☆☆GCP★★★☆☆★★★★☆★★★☆☆Kubernetes★★☆☆☆★★★★★★★★★☆Docker/Helm★☆☆☆☆★★★★☆★★★★☆
Comparative coverage matrix for IaC security scanners across cloud platforms and orchestration tools

For multi-cloud organizations, avoid forcing a single tool. Run tfsec for AWS/Terraform modules where it dominates, Checkov for Azure/GCP/K8s coverage, and aggregate results. The marginal CI time increase is worth avoiding blind spots. Document this matrix in your internal developer platform so teams self-select appropriate scanners based on their stack rather than guessing.

Start Securing Your Infrastructure Today

Effective IaC security: scan with tfsec, Checkov, Terrascan transforms infrastructure provisioning from a trust-based model to a verified, auditable process. Begin with tfsec in pre-commit hooks for immediate wins, layer Checkov for compliance reporting, and add Terrascan when you need deeper forensic context. Automate enforcement in CI, manage exceptions rigorously, and treat policy definitions as first-class code artifacts. If your team needs help designing a scanning strategy that balances security rigor with delivery speed, reach out to discuss your specific infrastructure challenges.

Frequently Asked Questions

tfsec focuses exclusively on Terraform with deep HCL parsing. Checkov supports multiple frameworks including Kubernetes and Docker alongside Terraform. Terrascan offers the broadest policy library covering cloud-native assets beyond just infrastructure code, making it ideal for comprehensive compliance auditing across mixed environments in 2026.

Yes, Aqua Security actively maintains tfsec as part of Trivy. While standalone tfsec works, migrating to trivy config provides unified scanning for IaC, containers, and dependencies using identical rule sets and better CI integration without losing any original tfsec functionality or performance benefits.

Install via pipx to avoid system Python conflicts by running pipx install checkov. Alternatively, use the official Docker image bridgecrew/checkov for isolated execution. Both methods ensure you get the latest 3.x release with updated policies for current AWS, Azure, and GCP provider versions.

No, they only scan local configuration files and plan outputs. For remote state, run terraform plan -out=tfplan.binary first, convert it to JSON, then pass that file to the scanner. This captures resolved values and module expansions unavailable in raw HCL source code alone.

tfsec typically produces fewer false positives due to its specialized HCL parser understanding Terraform-specific interpolation and module references. Checkov and Terrascan cast wider nets across multiple formats, occasionally flagging valid patterns as issues. Always validate findings against your specific architecture before blocking deployments in production pipelines.

They detect hardcoded secrets but miss environment variable leaks. Pair them with gitleaks or trufflehog for comprehensive secret detection. Configure custom rules to flag sensitive variable names lacking encryption markers or vault references, ensuring credentials never appear in state files or plan outputs during CI runs.

Add inline comments like # checkov:skip=CKV_AWS_18:reason directly above the resource block. For broader suppression, create a .checkov.yaml skip list. Always document justification for every skipped check to maintain audit trails and prevent security debt accumulation during future infrastructure refactors or compliance reviews.

Yes, all three are open-source and free for unlimited local and CI usage. Commercial versions offer enhanced policy packs, SaaS dashboards, and team management features. Most organizations find the open-source editions sufficient for core security gating, reserving paid tiers for enterprise compliance reporting and centralized policy enforcement.

All three provide official GitHub Actions. Checkov action offers the most configurable outputs including SARIF for code scanning alerts. tfsec action excels at PR comment annotations. Choose based on your existing workflow preferences rather than capability gaps, as feature parity exists across all major CI platforms in 2026.

Yes, Terrascan natively supports OPA Rego for custom policy authoring. Place .rego files in your policies directory and reference them via --policy-path flag. This enables organization-specific compliance rules beyond built-in checks while maintaining compatibility with standard OPA tooling and testing frameworks used elsewhere in your stack.

Update weekly or pin to specific versions tested against your infrastructure. New cloud services and CVEs emerge constantly, making outdated policies ineffective. Automate updates in non-production pipelines first to catch breaking changes before promoting to production gates where false positives could block legitimate deployments unexpectedly.

Yes, tfsec fully supports OpenTofu syntax and modules. Since OpenTofu maintains HCL compatibility, all existing tfsec rules apply without modification. Specify --tflint-backend=opentofu if needed for edge cases, though default behavior handles both Terraform and OpenTofu projects identically in current releases.

Use SARIF format for native integration with GitHub Code Scanning, GitLab SAST, or Azure DevOps. JSON works universally for custom parsing and dashboard ingestion. Avoid plain text in automated pipelines since structured formats enable trend tracking, deduplication, and actionable reporting that raw console output cannot provide effectively.

Yes, point scanners at root directories containing multiple modules. tfsec and Checkov recursively discover nested configurations automatically. For monorepos with dozens of modules, consider parallel execution or workspace-level scanning to reduce CI runtime while maintaining complete coverage across all infrastructure components and shared libraries.

Time each tool against identical codebases using time command. Expect tfsec under thirty seconds for medium projects, Checkov slightly longer due to multi-framework overhead, and Terrascan varying based on policy count. Profile memory usage too, as large state files can cause significant RAM consumption during analysis phases.