Auditing Terraform infrastructure-as-code for security misconfigurations using Checkov, tfsec, Terrascan, and OPA/Rego policies to detect overly permissive IAM policies, public resource exposure, missing encryption, and insecure defaults before cloud deployment.
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
Auditing Terraform infrastructure-as-code for security misconfigurations using Checkov, tfsec, Terrascan, and OPA/Rego policies to detect overly permissive IAM policies, public resource exposure, missing encryption, and insecure defaults before cloud deployment.
When integrating security scanning into CI/CD pipelines for Terraform deployments
When reviewing Terraform plans and modules for security best practices before applying
When building policy-as-code guardrails for cloud infrastructure provisioning
When auditing existing Terraform state files to identify deployed misconfigurations
When enforcing organizational security standards across multiple Terraform projects
Do not use for runtime security monitoring (use CSPM tools), for application security testing (use SAST/DAST tools), or for cloud configuration drift detection (use AWS Config or Azure Policy after deployment).
Detection Gaps & Validation
Scanning HCL source misses what's resolved at apply time: values from variables, locals, data sources, registry/remote modules, and count/for_each are unknown to a static checkov -d/tfsec pass. Scan the plan JSON (terraform show -json tfplan > tfplan.json; checkov -f tfplan.json --framework terraform_plan) to catch them.
Remote modules are skipped by default:tfsec --exclude-downloaded-modules and un-init'd modules mean a misconfig inside terraform-aws-modules/... is never seen. Run terraform init first and do not exclude downloaded modules.
Inline policies and heredocs slip through: IAM JSON in aws_iam_role_policy/aws_iam_policy.policy heredocs is often not parsed as policy; wildcard Action/Resource there can pass silently. Back stop with custom OPA/Conftest on the plan.
Suppressions and soft-fail hide failures:#checkov:skip=, tfsec:ignore:, and --soft-fail/soft_fail: true make CI green while findings exist. Grep for skip comments and require non-zero exit to block.
Verify the gate actually blocks: introduce a known-bad resource (unencrypted aws_s3_bucket, 0.0.0.0/0 ingress on 22) and confirm the pipeline fails; reconcile checkov/ resource counts against so state-only (drift / console-created) resources aren't assumed covered.
tfsec
terraform state list
Prerequisites
Checkov installed (pip install checkov)
tfsec installed (brew install tfsec or binary from GitHub)
Terrascan installed (brew install terrascan)
Terraform v1.0+ for plan generation
OPA (Open Policy Agent) for custom policy enforcement
Git repository with Terraform code to audit
Workflow
Step 1: Scan Terraform Code with Checkov
Run Checkov for comprehensive IaC security scanning with built-in and custom policies.
# Scan a Terraform directory
checkov -d ./terraform/ --framework terraform
# Scan with specific check categories
checkov -d ./terraform/ --check CKV_AWS_18,CKV_AWS_19,CKV_AWS_20,CKV_AWS_21
# Scan and output results in JSON
checkov -d ./terraform/ --output json > checkov-results.json
# Scan a Terraform plan file for more accurate analysis
terraform init && terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
checkov -f tfplan.json --framework terraform_plan
# Skip specific checks with justification
checkov -d ./terraform/ --skip-check CKV_AWS_145 \
--bc-api-key $BRIDGECREW_API_KEY# Scan Terraform modules
checkov -d ./modules/ --framework terraform --compact
# List all available checks
checkov --list --framework terraform | grep CKV_AWS
Step 2: Scan with tfsec for Terraform-Specific Issues
Use tfsec for Terraform-native security analysis with detailed remediation guidance.
# Scan a Terraform directory
tfsec ./terraform/
# Scan with minimum severity threshold
tfsec ./terraform/ --minimum-severity HIGH
# Output in JSON for CI/CD processing
tfsec ./terraform/ --format json > tfsec-results.json
# Scan with custom checks
tfsec ./terraform/ --custom-check-dir ./custom-checks/
# Exclude specific rules
tfsec ./terraform/ --exclude-downloaded-modules \
--exclude aws-s3-enable-bucket-logging
# Scan and fail on specific severity
tfsec ./terraform/ --minimum-severity CRITICAL --soft-fail
# Generate SARIF output for GitHub Security tab
tfsec ./terraform/ --format sarif > tfsec.sarif
Step 3: Run Terrascan for Multi-Framework Compliance
Execute Terrascan for compliance checking against CIS, NIST, and SOC 2 frameworks.
# Evaluate Terraform plan against OPA policies
terraform show -json tfplan | opa eval \
--data ./policy/ \
--input /dev/stdin \
"data.terraform.aws" \
--format pretty
# Run Conftest for easier OPA policy testing
conftest test tfplan.json --policy ./policy/ --output json
Step 5: Integrate Security Scanning into CI/CD Pipeline
Add IaC security scanning as a mandatory CI/CD gate.
# GitHub Actions: Terraform security pipelinename:TerraformSecurityScanon:pull_request:paths: ['terraform/**']
jobs:security-scan:runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-name:SetupTerraformuses:hashicorp/setup-terraform@v3-name:TerraformInit&Planrun:|
cd terraform/
terraform init
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
-name:CheckovScanuses:bridgecrewio/checkov-action@masterwith:directory:terraform/framework:terraformoutput_format:sarifoutput_file_path:checkov.sarifsoft_fail:false-name:tfsecScanuses:aquasecurity/tfsec-action@v1.0.0with:working_directory:terraform/soft_fail:false-name:UploadSARIFuses:github/codeql-action/upload-sarif@v2with:sarif_file:checkov.sarif-name:OPAPolicyCheckrun:|
conftest test terraform/tfplan.json \
--policy ./policy/ \
--output json
Step 6: Scan Terraform State for Deployed Misconfigurations
Audit the current Terraform state to identify already-deployed security issues.
# Export current state as JSON
terraform show -json > terraform-state.json
# Scan the state with Checkov
checkov -f terraform-state.json --framework terraform_plan
# Query state for specific security issues
terraform state list | whileread resource; do
terraform state show "$resource" 2>/dev/null | grep -i "public\|0.0.0.0\|encrypt.*false\|password"done# Find resources without required tags
terraform state list | grep aws_instance | whileread resource; do
tags=$(terraform state show "$resource" | grep -A20 "tags")
if ! echo"$tags" | grep -q "Environment"; thenecho"MISSING TAG: $resource lacks 'Environment' tag"fidone
Key Concepts
Term
Definition
Infrastructure as Code
Practice of managing cloud infrastructure through declarative configuration files (Terraform, CloudFormation) rather than manual console operations
Policy as Code
Expressing security and compliance policies as executable code (Rego, Python) that can be automatically evaluated against infrastructure definitions
Shift Left Security
Moving security checks earlier in the development lifecycle by scanning IaC before deployment rather than auditing after provisioning
Terraform Plan
Preview of changes Terraform will make, which can be exported as JSON for security scanning before applying changes
Checkov
Open-source static analysis tool for IaC supporting Terraform, CloudFormation, Kubernetes, and Docker with 1000+ built-in policies
OPA/Rego
Open Policy Agent and its policy language Rego for defining custom security rules that evaluate against structured data inputs
Tools & Systems
Checkov: Comprehensive IaC scanner with 1000+ policies for Terraform, CloudFormation, Kubernetes, ARM, and Dockerfile
tfsec: Terraform-specific static analysis tool with detailed remediation guidance and SARIF output
OPA/Conftest: Custom policy engine for defining organization-specific security rules using Rego language
Bridgecrew: Commercial platform built on Checkov providing drift detection and supply chain security
Common Scenarios
Scenario: Adding Security Gates to an Existing Terraform CI/CD Pipeline
Context: A DevOps team deploys infrastructure via Terraform in GitHub Actions but has no security scanning. Recent audit findings show multiple S3 buckets without encryption and security groups allowing SSH from the internet.
Approach:
Add Checkov as the first security gate in the GitHub Actions workflow
Run checkov -d ./terraform/ to establish the current baseline of findings
Configure the pipeline to block PRs with CRITICAL or HIGH findings
Generate SARIF reports for GitHub Security tab integration
Pitfalls: Adding security scanning to an existing project will initially produce hundreds of findings. Implement gradually by starting with CRITICAL-only blocking, then expanding to HIGH. Use inline suppression comments (#checkov:skip=CKV_AWS_18:Public bucket for static website) for intentional exceptions with documented justification.