IaC Misconfigurations and Scanning with Trivy
When infrastructure is written as code (Terraform or OpenTofu, CloudFormation, Bicep, Kubernetes manifests, Helm charts), most of the misconfigurations in this course exist as text before they exist in an account: the public bucket, the database open to the Internet, the trail without log validation. That is the cheapest moment to catch them: a pull-request comment costs minutes, a finding in production costs an incident review. IaC scanners parse the code and check every resource against a library of rules. They are also easy to over-trust: they check what their rules know, on the values they can resolve, and nothing else. This lesson runs Trivy (whose IaC engine absorbed the former tfsec) on Terraform and CloudFormation, fixes the findings, and looks hard at what it didn't report. Linting with tflint and the Terraform toolkit cover the builder's tooling; Conftest on Terraform Plans policy checks on plans.
Where scanners fit
| Stage | Tool examples | Sees |
|---|---|---|
| Editor / pre-commit | Trivy, Checkov, KICS, tflint | the files being changed |
| Pull request (CI) | the same, plus policy-as-code on the plan (OPA/Conftest, Sentinel) | the whole module, and with a plan the resolved values |
| Deployment | admission and organisation guardrails (SCPs, Azure Policy, org policies) | the real API request |
| Running account | CSPM (the next section) | what actually exists, including changes made outside IaC |
Static file scanning sees literal values and simple expressions; it can't know a variable's value from another workspace or what a module from a registry contains unless it is downloaded. Scanning the plan (terraform show -json plan.out) closes most of that gap.
A first scan
The session writes a small Terraform configuration for the lab's database and audit trail, and a CloudFormation template written by another team, then scans both. It runs in your sandbox on local files; nothing is deployed.
mkdir tf cfn
cat > tf/main.tf <<'TF'
resource "aws_db_instance" "shop" {
identifier = "shop-db"
engine = "postgres"
instance_class = "db.t4g.micro"
allocated_storage = 20
username = "shop"
password = "Wq7!vR2#kd9Lp0sZ"
publicly_accessible = true
storage_encrypted = false
}
resource "aws_cloudtrail" "org" {
name = "org-trail"
s3_bucket_name = "lab-trail-123456789012"
}
resource "aws_iam_policy" "ci" {
name = "ci-deploy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{ Effect = "Allow", Action = "*", Resource = "*" }]
})
}
TF
cat > cfn/stack.yaml <<'Y'
AWSTemplateFormatVersion: "2010-09-09"
Resources:
Uploads:
Type: AWS::S3::Bucket
Properties:
BucketName: lab-cfn-uploads
AppQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: app-jobs
Y
for d in tf cfn; do
echo "== $d: $(trivy config -q -f json $d | jq '[.Results[].Misconfigurations[]?] | length') findings"
trivy config -q -f json $d | jq -r '[.Results[].Misconfigurations[]?] | sort_by(.ID)[] | " \(.Severity) \(.ID) \(.Title)"'
done== tf: 10 findings
MEDIUM AWS-0014 Cloudtrail should be enabled in all regions regardless of where your AWS resources are generally homed
HIGH AWS-0015 CloudTrail should use Customer managed keys to encrypt the logs
HIGH AWS-0016 Cloudtrail log validation should be enabled to prevent tampering of log data
MEDIUM AWS-0077 RDS Cluster and RDS instance should have backup retention longer than default 1 day
HIGH AWS-0080 RDS encryption has not been enabled at a DB Instance level.
LOW AWS-0133 Enable Performance Insights to detect potential problems
LOW AWS-0162 CloudTrail logs should be stored in S3 and also sent to CloudWatch Logs
MEDIUM AWS-0176 RDS IAM Database Authentication Disabled
MEDIUM AWS-0177 RDS Deletion Protection Disabled
HIGH AWS-0180 RDS Publicly Accessible
== cfn: 9 findings
HIGH AWS-0086 S3 Access block should block public ACL
HIGH AWS-0087 S3 Access block should block public policy
LOW AWS-0089 S3 Bucket Logging
MEDIUM AWS-0090 S3 Data should be versioned
HIGH AWS-0091 S3 Access Block should Ignore Public ACL
HIGH AWS-0093 S3 Access block should restrict public bucket to limit access
LOW AWS-0094 S3 buckets should each define an aws_s3_bucket_public_access_block
HIGH AWS-0096 Unencrypted SQS queue.
HIGH AWS-0132 S3 encryption should use Customer Managed Keys
Ten findings in three Terraform resources and nine in two CloudFormation resources. The useful ones map directly onto earlier lessons: RDS publicly accessible and unencrypted (exposure, KMS), CloudTrail without log file validation and not multi-region (audit logs), the bucket without Block Public Access (object storage), the unencrypted queue. Others (Performance Insights, CloudWatch delivery) are good practice rather than security-critical; severity ratings are the tool's opinion and should be mapped to your own policy.
Now read the list for what is missing. Two serious problems produced no finding at all:
- The IAM policy
ci-deploygrants"Action": "*"on"Resource": "*": administrator. In this Trivy version and this way of writing it, no rule fired. - The database password is a literal in the code, so it sits in the repository and in the state file (where secrets hide).
Neither is exotic. They show the limit of rule libraries: a rule must exist, must match the way the code is written (jsonencode, a heredoc, a data source, a module), and must be able to resolve the value. The next lesson writes custom checks for exactly these two.
Fixing and gating
The fixed Terraform below addresses every finding of the first scan (the IAM policy is left out until the next lesson gives us a check for it), and the session uses Trivy as a gate: --severity HIGH,CRITICAL --exit-code 1 fails the CI job when anything at that level remains.
mkdir tf
cat > tf/main.tf <<'TF'
resource "aws_db_instance" "shop" {
identifier = "shop-db"
engine = "postgres"
instance_class = "db.t4g.micro"
allocated_storage = 20
username = "shop"
manage_master_user_password = true
publicly_accessible = false
storage_encrypted = true
kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/11111111-2222-3333-4444-555555555555"
iam_database_authentication_enabled = true
deletion_protection = true
backup_retention_period = 14
performance_insights_enabled = true
performance_insights_kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/11111111-2222-3333-4444-555555555555"
}
resource "aws_cloudtrail" "org" {
name = "org-trail"
s3_bucket_name = "lab-trail-123456789012"
is_multi_region_trail = true
is_organization_trail = true
enable_log_file_validation = true
kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/11111111-2222-3333-4444-555555555555"
cloud_watch_logs_group_arn = "arn:aws:logs:eu-west-1:123456789012:log-group:org-trail:*"
cloud_watch_logs_role_arn = "arn:aws:iam::123456789012:role/trail-to-logs"
}
TF
trivy config -q --severity HIGH,CRITICAL --exit-code 1 -f json tf > gate.json
echo "gate exit code: $?"
echo "remaining (any severity): $(trivy config -q -f json tf | jq '[.Results[].Misconfigurations[]?] | length')"gate exit code: 0
remaining (any severity): 0
The gate passes, and nothing at lower severity remains either. Note manage_master_user_password = true: RDS generates the password and keeps it in Secrets Manager, so it never appears in code or state.
How IaC findings are managed
- Gate on severity, report the rest: fail pull requests on HIGH and CRITICAL, comment the others.
- Exceptions in code, next to the resource (
#trivy:ignore:AWS-0089inline comments or a.trivyignoreentry) with a reason and, where the tool supports it, an expiry. Exceptions reviewed like code. - Scan modules and plans, not just the root files; vendor or download external modules in CI so their contents are scanned.
- Compare scanners occasionally on the same code: their rule sets differ, and the differences are where your custom policies belong.
Pitfalls
- "The scanner is green" read as "the infrastructure is secure": it means "no known rule matched the parts it could read".
- Suppressing whole rule IDs repository-wide to make the pipeline pass.
- Scanning only Terraform while a quarter of the infrastructure is created by hand, by CloudFormation from another team, or by Helm: scan every IaC format in use, and use posture management for the rest.
Practice
1. In the first scan, which finding would you fix first, and why that one?
AWS-0180 RDS Publicly Accessible: combined with a security group that allows the Internet, it exposes the database directly (latent exposure). Encryption and CloudTrail validation follow; Performance Insights can wait.
2. Why does manage_master_user_password fix a problem the scanner didn't report?
The literal password was never flagged, but it lived in the repository and state. With the managed password, RDS creates and rotates it in Secrets Manager and the Terraform code has nothing secret in it.
3. Your team uses a public Terraform module for the VPC. How do you make sure it is scanned?
Run terraform init in CI so the module is downloaded into .terraform/modules, then scan the directory (Trivy follows module sources it can resolve locally), and scan the plan JSON for resolved values. Pin the module version so the scanned code is the deployed code.
Test yourself
Which serious problems in the first Terraform file did Trivy not report?
- Public RDS and missing encryption
- The Action * IAM policy and the literal database password
- CloudTrail log validation
- Nothing was missed
What do --severity HIGH,CRITICAL --exit-code 1 do in CI?
- Hide findings
- Make the job fail when any HIGH or CRITICAL finding remains
- Upload results
- Fix findings
Why scan the Terraform plan as well as the files?
- Plans are smaller
- The plan has resolved values from variables and modules that static file parsing can't see
- Scanners only read plans
- Plans include costs
What does a green IaC scan actually tell you?
- The account is secure
- No known rule matched the code the scanner could read
- There are no secrets anywhere
- The deployment succeeded