Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท DevSecOps

Infrastructure as Code Scanning

Find cloud misconfigurations before deployment: how IaC scanners read Terraform, CloudFormation and Kubernetes files, common findings, fixes, suppressions and plan scanning.

Infrastructure as Code (IaC) describes servers, networks, storage and permissions in text files, such as Terraform, AWS CloudFormation, Azure Bicep, Pulumi or Kubernetes manifests, instead of clicking through a console. That brings version control, review and repeatability. It also means that one insecure line of code can be copied into a hundred environments. The good news is that text can be analysed before anything is created.

IaC scanning is static analysis for infrastructure: a tool reads the files, applies a library of rules and reports misconfigurations in a pull request, long before they reach the cloud. In this lesson you will read the typical findings, see what scanner output looks like, learn how the tools work and write a small scanner of your own.

All Terraform in this lesson is illustrative and is never applied. The runnable scanner reads text in your browser and creates nothing.

What scanners catch

Most IaC rules are the same checks you saw in posture management, moved earlier:

  • Storage that is public, unencrypted or without versioning or access logging.
  • Security groups or firewall rules open to 0.0.0.0/0 on sensitive ports.
  • Databases with public endpoints, no encryption, no backups or no TLS.
  • IAM policies with * actions or resources, and roles that anyone can assume.
  • Missing logging, such as CloudTrail disabled or no flow logs.
  • Hard-coded secrets in variables and defaults.
  • Kubernetes manifests with privileged containers, root users and latest tags.
  • Missing tags or encryption keys that policy requires.

A vulnerable Terraform example (read-only)

HCL
resource "aws_s3_bucket" "uploads" {
  bucket = "example-uploads"
  acl    = "public-read"
}

resource "aws_security_group_rule" "admin" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = "sg-12345"
}

resource "aws_db_instance" "main" {
  engine              = "postgres"
  publicly_accessible = true
  storage_encrypted   = false
  password            = "SuperSecret123"
}

A scanner would flag a public bucket, SSH open to the world, a public and unencrypted database and a hard-coded password. Output from a tool such as Checkov or Trivy looks similar to this labelled sample (rule names are illustrative):

TEXT
# SAMPLE OUTPUT (illustrative)
Check: S3 bucket must not be public          FAILED  aws_s3_bucket.uploads   main.tf:1-4
Check: No ingress from 0.0.0.0/0 to port 22  FAILED  aws_security_group_rule.admin  main.tf:6-13
Check: RDS must not be publicly accessible   FAILED  aws_db_instance.main     main.tf:15-20
Check: RDS storage must be encrypted         FAILED  aws_db_instance.main     main.tf:15-20
Check: No hard-coded password                FAILED  aws_db_instance.main     main.tf:15-20

The fixed version

HCL
resource "aws_s3_bucket" "uploads" {
  bucket = "example-uploads"
}

resource "aws_s3_bucket_public_access_block" "uploads" {
  bucket                  = aws_s3_bucket.uploads.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_security_group_rule" "admin" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["10.0.0.0/16"]   # internal range only
  security_group_id = "sg-12345"
}

resource "aws_db_instance" "main" {
  engine                      = "postgres"
  publicly_accessible         = false
  storage_encrypted           = true
  manage_master_user_password = true   # password lives in a secret manager
}

How a scanner works

flowchart LR
    A["IaC files"] --> B["Parse to a graph<br/>resources, attributes, references"]
    B --> C["Resolve variables and modules"]
    C --> D["Apply rules"]
    D --> E["Report with file and line"]
    E --> F["Fail or warn in CI"]

Better scanners resolve variables and references, because the danger often hides behind a variable or module.

Parsers turn HCL, YAML or JSON into a tree of resources. Rules then examine attributes: "if type is a bucket and ACL is public-read, report". Advanced rules follow references (does the bucket have a matching public access block?). A deeper option is to scan the plan: terraform plan -out=tfplan followed by terraform show -json tfplan produces the final resolved values, which catches issues that only exist after variables and modules expand.

Try it: a mini IaC scanner

This stand-in parses a simplified resource syntax with regular expressions (real tools use proper HCL parsers) and applies rules, reporting line numbers.

Python Scan simplified Terraform text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output matches the sample output above, in miniature. A real tool resolves variables, handles nested blocks and ships hundreds of rules, but the cycle of parse, apply rules, report with location is the same.

Scanning Kubernetes manifests and Dockerfiles

The same approach works for YAML. A rule might check that every container sets runAsNonRoot: true and drops capabilities, as covered in Kubernetes security basics, or that a Dockerfile defines a USER (container image security).

Python Check a Kubernetes manifest (as data) for a risky setting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Using IaC scanning well

  • Run it in three places: the editor or pre-commit hook for instant feedback, the pull request as a gate and a scheduled scan of the main branch to catch new rules.
  • Scan plans as well as source to see resolved values and modules.
  • Handle suppressions explicitly. Most tools let you annotate a resource to skip a rule (#checkov:skip=CKV_AWS_18:reason). Require a written reason, review suppressions like code and set expiry reminders.
  • Fix the module, not every copy. Put secure defaults into shared modules, so a fix reaches every consumer.
  • Combine with policy as code for organisation-specific rules (policy as code) and with live scanning for drift.
  • Remember what scanners cannot see: runtime behaviour, secrets that arrive from outside the repository and resources created by hand. They complement, not replace, monitoring.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of scanning IaC files before deployment?

    Static analysis of templates catches mistakes in the pull request, where fixing them costs almost nothing.
  2. 2. Why scan the Terraform plan JSON in addition to source files?

    The final values may depend on variables or modules. The plan shows what will actually be created.
  3. 3. A rule is suppressed on one resource. What should accompany the suppression?

    Unexplained suppressions become hidden risks. Treat them as reviewed, expiring exceptions.
  4. 4. Which is the best way to prevent the same insecure setting appearing in many projects?

    Secure shared modules make the safe configuration the default for everybody who uses them.

Summary

  • IaC scanners analyse Terraform, CloudFormation, Kubernetes and similar files for misconfiguration before deployment.
  • Findings are the familiar ones: public storage, open ports, unencrypted databases, wildcard IAM, hard-coded secrets and missing logs.
  • Good tools parse to a graph, resolve variables and modules and can scan plan output.
  • Run scans in the editor, pull request and on a schedule; manage suppressions carefully; fix shared modules.
  • Static scanning complements policy as code, live posture checks and monitoring.

Next: Secrets Scanning and Management in Pipelines