Lesson 21 / 31
Infrastructure as Code Scanning
Catch cloud misconfigurations such as public buckets and open SSH in Terraform before they are applied.
By Rahul Agarwal · 15 years in web development
Misconfiguration is the common breach
Many cloud incidents are not clever exploits but misconfigurations: a storage bucket readable by the public, a database with a public IP, a security group allowing SSH from 0.0.0.0/0, logging turned off, encryption missing. When infrastructure is defined as code with Terraform, OpenTofu, CloudFormation, Kubernetes manifests or Helm charts, those mistakes are visible in a pull request, so they can be caught before anything exists. IaC scanners such as Checkov, Trivy (trivy config, which absorbed the older tfsec checks) and KICS parse the files and apply hundreds of built-in rules mapped to benchmarks like the CIS benchmarks. Scanning the plan (terraform show -json output) catches values that only resolve at plan time. Pair IaC scanning with drift detection, because a console click in production can reintroduce the very problem your code fixed.
A Terraform security group that a scanner flags
Opening SSH to the whole internet is one of the most common findings. The fixed rule allows only the office VPN range.
resource "aws_security_group_rule" "ssh_bad" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # flagged: SSH open to the world
security_group_id = aws_security_group.app.id
}
resource "aws_security_group_rule" "ssh_ok" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.20.0.0/16"] # VPN range only
security_group_id = aws_security_group.app.id
}
# scan: trivy config ./infra or checkov -d ./infraPrefer no SSH at all
The best fix for open SSH is often removing it: use your cloud's session manager or an identity-aware proxy, which gives audited access without an open port.
Quick check: Why scan the Terraform plan JSON in addition to the .tf files?
- Plan files are smaller
- Some values, such as variables and module outputs, are only resolved at plan time
- Scanners cannot read .tf files
- The plan contains the cloud provider's password
Answer
Some values, such as variables and module outputs, are only resolved at plan time — Static .tf files may contain variables whose real values appear only in the plan, so plan scanning sees the final configuration.