0Pricing
Cloud & IT Cert Prep · Lesson

Infrastructure as Code Security Scanning

Scan Terraform, CloudFormation, and Helm charts with IaC security tools (Checkov, tfsec) to catch misconfigurations before they reach production.

Infrastructure as Code Security Scanning is a free Cloud & IT Cert Prep lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cloud & IT Cert Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Infrastructure as Code Security Overview

Infrastructure as Code (IaC) tools like Terraform, AWS CloudFormation, Ansible, and Helm allow infrastructure to be defined in version-controlled configuration files. This brings enormous benefits — repeatability, auditability, and automation — but also a critical security risk: misconfigurations in IaC files produce insecure infrastructure at scale. A single misconfigured Terraform module deployed across 50 environments creates 50 vulnerable systems simultaneously. IaC security scanning addresses this by checking configuration files before they are applied, shifting security left into the developer workflow.

Common IaC Misconfigurations

Security scanning tools look for the most common IaC misconfigurations found in real-world cloud environments: S3 buckets with public access enabled or no encryption at rest; security groups with 0.0.0.0/0 inbound rules on sensitive ports (22, 3389, 1433); databases without encryption or with public accessibility; IAM policies with * resource or action wildcards; CloudTrail disabled in a region; KMS keys without key rotation; and load balancers with HTTP listeners instead of HTTPS. These findings closely mirror the checks performed by cloud security benchmarks like CIS AWS Foundations.

# Dangerous Terraform: public S3 bucket + no encryption
resource 'aws_s3_bucket' 'data' {
  bucket = 'my-data-bucket'
  # Missing: server_side_encryption_configuration
  # Missing: aws_s3_bucket_public_access_block
}

Checkov: Policy as Code for IaC

Checkov (by Bridgecrew/Prisma Cloud) is a popular open-source static analysis tool for IaC that supports Terraform, CloudFormation, Kubernetes manifests, Helm charts, and Dockerfiles. It ships with over 1,000 built-in policies mapped to CIS benchmarks, GDPR, SOC 2, and HIPAA. Running checkov -d . scans all IaC files in the current directory and produces a color-coded report of passed, failed, and skipped checks with resource paths and remediation guidance. Checkov can be integrated into CI/CD pipelines to block deployments when critical checks fail.

# Install and run Checkov on Terraform files
pip install checkov
checkov -d ./terraform/ --framework terraform

# Fail CI pipeline on HIGH severity findings
checkov -d ./terraform/ --check HIGH --hard-fail-on HIGH

tfsec: Terraform Security Scanner

tfsec (now part of Trivy's IaC scanning capability) is a purpose-built Terraform security scanner that understands HCL syntax deeply, allowing it to trace values across modules and variable files. Unlike simpler scanners, tfsec can detect misconfigurations where the issue spans multiple files — for example, a security group rule that appears safe in isolation but is attached to a resource in another file. tfsec produces findings with severity levels (CRITICAL, HIGH, MEDIUM, LOW), CWE IDs, and direct links to remediation documentation, making findings actionable for developers.

# Install tfsec and scan Terraform directory
brew install tfsec
tfsec ./terraform/ --format json

# Or use Trivy for unified IaC + container scanning
trivy config ./terraform/

Secrets in IaC Files

One of the most critical IaC security issues is hardcoded secrets in configuration files — passwords, API keys, TLS private keys, and database connection strings committed to Git. Since IaC repositories are often shared across teams and stored in version control history, a secret committed even once is effectively compromised permanently (Git history is immutable). Tools like Checkov, detect-secrets, git-secrets, and TruffleHog scan for secret patterns. The fix is using input variables referenced from environment variables or secret stores, never hardcoded values.

# Bad: hardcoded password in Terraform
resource 'aws_db_instance' 'main' {
  password = 'supersecret123'  # NEVER DO THIS
}

# Good: read from variable, inject from secrets manager
variable 'db_password' { sensitive = true }
resource 'aws_db_instance' 'main' {
  password = var.db_password
}

Policy as Code: OPA and Sentinel

Policy as Code (PaC) frameworks allow security teams to write custom rules in code and enforce them consistently. Open Policy Agent (OPA) with Conftest allows writing Rego policies that validate any structured data — Terraform plans, Kubernetes manifests, Helm values — in CI/CD pipelines. HashiCorp Sentinel is built into Terraform Enterprise and Cloud, allowing policies like 'all S3 buckets must have encryption enabled' to be enforced at plan time, blocking any apply that would violate the policy. These tools allow security requirements to be codified and version-controlled alongside the infrastructure they govern.

# Example Conftest OPA policy: deny public S3
# deny[msg] {
#   input.resource.aws_s3_bucket[name]
#   input.resource.aws_s3_bucket_public_access_block == null
#   msg := sprintf('Bucket %v lacks public access block', [name])
# }

Drift Detection: Configuration vs Reality

Configuration drift occurs when the actual state of deployed infrastructure deviates from the IaC definition — often because someone made a manual change through the cloud console. A security group rule added manually to 'temporarily' unblock a developer becomes a permanent gap. Drift detection tools continuously compare the desired state (IaC files) against the actual deployed state and alert on deviations. AWS Config, Terraform Cloud's drift detection, and CSPM tools (Prisma Cloud, Wiz) all provide this capability. Security misconfigurations introduced through console changes are caught before attackers discover them.

# Terraform: detect drift between state and actual cloud resources
terraform plan -refresh-only
# If output shows changes, someone modified infrastructure outside Terraform

Immutable Infrastructure and GitOps

Immutable infrastructure means that servers and configurations are never modified in place — instead, changes create new resources (new AMIs, new container images) and replace old ones. Combined with GitOps (where all infrastructure changes must flow through a Git pull request, triggering IaC scanning and approval workflows), this eliminates configuration drift by construction: if something cannot be changed manually, it cannot drift. Tools like ArgoCD for Kubernetes and Atlantis for Terraform implement GitOps workflows where any deviation triggers an automatic reconciliation or alert.

SAST vs IaC Scanning Distinction

IaC security scanning is sometimes confused with SAST (Static Application Security Testing), but they target different artifacts. SAST analyzes application source code (Python, Java, JavaScript) for vulnerabilities like SQL injection or buffer overflows. IaC scanning analyzes infrastructure configuration files for cloud security misconfigurations — no application code is involved. A complete DevSecOps pipeline includes both: SAST on application code and IaC scanning on infrastructure files. Both run in CI/CD before any deployment. Some unified platforms (Snyk IaC, Prisma Cloud) combine application and infrastructure scanning in a single tool.

Integrating IaC Scanning Into CI/CD

Effective IaC security scanning must be automated and enforced — not optional. A typical CI/CD integration: on every pull request, run Checkov and tfsec; fail the pipeline if CRITICAL findings exist; post findings as pull request comments for developer visibility; maintain a list of suppressed findings with documented justifications; and run a nightly scan against deployed resources for drift. Pre-commit hooks using tools like pre-commit with Checkov can catch issues even before code reaches the pipeline. False positive management is important — developers who see too many irrelevant findings start ignoring them.

# GitHub Actions: IaC security scanning
# - name: Run Checkov IaC Scan
#   uses: bridgecrewio/checkov-action@master
#   with:
#     directory: terraform/
#     framework: terraform
#     soft_fail: false  # fail PR on findings
#     output_format: sarif  # upload to GitHub Security tab

Terraform State Security

Terraform's state file (terraform.tfstate) contains the complete inventory of all managed resources, often including sensitive output values like database passwords, TLS private keys, and IAM access key IDs in plaintext. State files must never be committed to Git. Instead, use a remote backend (AWS S3 with DynamoDB locking, Terraform Cloud, or GitLab-managed state) with server-side encryption enabled. Access to the state backend must be strictly controlled via IAM — anyone who can read the state file can enumerate all infrastructure details and potentially extract embedded secrets.

# Secure Terraform remote backend
terraform {
  backend 's3' {
    bucket         = 'my-terraform-state'
    key            = 'prod/terraform.tfstate'
    region         = 'us-east-1'
    encrypt        = true
    kms_key_id     = 'arn:aws:kms:us-east-1:123:key/abc'
    dynamodb_table = 'terraform-state-lock'
  }
}

Quick Check

Test your understanding of CompTIA Security+ (SY0-701) concepts from this lesson.

Lesson Recap

In this lesson you learned: IaC misconfigurations like public S3 buckets, open security groups, and hardcoded secrets are automatically detected by tools like Checkov and tfsec before deployment, Policy as Code frameworks (OPA/Conftest, HashiCorp Sentinel) allow custom organizational security requirements to be enforced as automated pipeline gates, and Terraform state files must be stored in encrypted remote backends with strict access controls as they may contain sensitive resource details. Next up we explore the APT lifecycle and how advanced threats persist inside networks.

Frequently asked questions

Is the “Infrastructure as Code Security Scanning” lesson free?

Yes — the full text of “Infrastructure as Code Security Scanning” is free to read here on the web, and the Cloud & IT Cert Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cloud & IT Cert Prep course, upgrade to CoddyKit PRO.

What will I learn in “Infrastructure as Code Security Scanning”?

Scan Terraform, CloudFormation, and Helm charts with IaC security tools (Checkov, tfsec) to catch misconfigurations before they reach production. You practise Cloud & IT Cert Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Cloud & IT Cert Prep?

No prior experience is required. Cloud & IT Cert Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Infrastructure as Code Security Scanning” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Cloud & IT Cert Prep lesson?

Yes. Every Cloud & IT Cert Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Container Security: Image Hardening and Runtime Protection
  2. Kubernetes Security: RBAC, Network Policies, and Pod Security
  3. Serverless and Function Security
  4. Infrastructure as Code Security Scanning
← Back to Cloud & IT Cert Prep