Testing and Security Guardrails
7 min read
Welcome to Section 11.
If terraform apply gives you a slight panic attack, your heart rate spikes, and you silently pray to the cloud gods that you didn't just delete the production database... you are in the right place. π§
In the early days of DevOps, we called this "YOLO Ops." You wrote code, applied it, and fixed the fires later. Today, we have Guardrails.
This section moves you from "I hope this works" to "I prove this works before I merge."
1. Static Code Analysis: Securing Code with tfsec
The Problem
You are writing Terraform to create an AWS S3 bucket. You accidentally copy-paste a snippet from StackOverflow from 2016 that sets the bucket to "Public." You apply it. Within 4 minutes, a bot finds it and uploads 10TB of cat memes (or crypto miners).
The Solution: Static Application Security Testing (SAST)
Static analysis tools read your code text files without actually creating resources. They look for patterns that match known security vulnerabilities.
We will use tfsec.
Note: tfsec has technically been acquired by Aqua Security and is merging into trivy, but tfsec is still the industry standard standalone binary used in most pipelines today.
π οΈ Hands-On: Setting up tfsec
Installation:
- MacOS (Homebrew):
brew install tfsec - Windows (Chocolatey):
choco install tfsec - Linux:
curl -s https://raw.githubusercontent.com/aquasecurity/tfsec/master/scripts/install_linux.sh | bash
The Scenario:
Create a file named bad_bucket.tf:
resource "aws_s3_bucket" "bad_example" {
bucket = "my-sketchy-bucket"
acl = "public-read" # π© RED FLAG
}
resource "aws_security_group" "bad_sg" {
name = "allow_all"
ingress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"] # π© RED FLAG: The whole internet
}
}Run the Analysis:
In your terminal, simply run:
tfsec .The Output:
You will see a beautiful (and terrifying) list of failures.
Result #1 HIGH Bucket has a public ACL.
...
Result #2 CRITICAL Security group rule allows ingress from public internet.Practical Tip:
Sometimes you need to break a rule (e.g., a public web server needs port 80 open). You can ignore rules by adding a comment code provided by tfsec output:
resource "aws_security_group" "web_server" {
#tfsec:ignore:aws-vpc-no-public-ingress-sgr
ingress {
from_port = 80 ...
}
}Fun Fact: The 2019 Capital One data breach, one of the largest in history, was largely attributed to a misconfigured web application firewall and permissions. Tools like
tfsecorCheckovare designed specifically to catch these "misconfigurations" before they exist in the cloud.
2. Cost Estimation: Catching Surprises with Infracost
The Problem
Cloud bills are like going to a sushi restaurant with a conveyor belt. You grab plates (resources) thinking "this looks good," and then you have a heart attack when the check comes.
The Solution
Infracost sits between your coding and your applying. It reads your Terraform plan, looks up the current API pricing for those specific resources (instance types, storage size, regions), and tells you how much it will cost per month.
π οΈ Hands-On: Setting up Infracost
Installation:
- MacOS (Homebrew):
brew install infracost - Windows (Chocolatey):
choco install infracost
Setup:
You need a free API key (this is how they fetch live cloud pricing).
infracost registerThe Scenario:
Let's see how much a "cheap" server costs. Create main.tf:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "my_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.medium" # Changing from t2.micro
}Run the Estimate:
Infracost works best by analyzing the Breakdown:
infracost breakdown --path .The Output:
OVERALL TOTAL $30.37
ββββββββββββββββββββββββββββββ
aws_instance.my_server
ββ Instance usage (Linux/UNIX, on-demand, t3.medium) $29.20
ββ root_block_device
ββ Storage (general purpose SSD, gp3) $1.17Industry Standard:
Developers usually run this in a Pull Request (PR). If a developer changes a t3.medium to a m5.4xlarge, Infracost will post a comment on the PR saying: "β οΈ This change will increase the monthly bill by $1,200."
3. Automated Testing: Introduction to Terratest
The Problem
terraform plan tells you what API calls it will make. It does not tell you if the server actually boots up, if the app installs correctly, or if the load balancer is actually listening.
The Solution: Integration Testing
We need to actually deploy the infrastructure, run a script to check if it works (e.g., ping it), and then destroy it immediately so we don't pay for it.
Enter Terratest.
Terratest is a Go (Golang) library developed by Gruntwork.
Warning: You need to write Go code. Don't panic. You don't need to be a Go expert; you just need to know how to copy-paste the boilerplate patterns.
π οΈ Hands-On: A Basic Test
Prerequisites:
- Install Go:
brew install go(or download from golang.org) - Create a folder
testinside your project.
The Workflow:
- Init: Terraform Init/Apply.
- Validate: Run code to check infrastructure (HTTP request, SSH command).
- Teardown: Terraform Destroy (ALWAYS happens, even if test fails).
The Code (test/terraform_basic_test.go):
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestTerraformAwsExample(t *testing.T) {
// 1. Configure where the terraform code is
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../examples/web-server",
})
// 2. Defer the destroy. This runs at the END, no matter what.
defer terraform.Destroy(t, terraformOptions)
// 3. Init and Apply
terraform.InitAndApply(t, terraformOptions)
// 4. Validate. Let's grab an output variable (like an IP address)
publicIp := terraform.Output(t, terraformOptions, "public_ip")
// 5. Assert (Check if it's not empty)
assert.NotEmpty(t, publicIp)
}Run the test:
cd test
go test -vWhat happens under the hood?
You will see your terminal fly through logs. It will spin up real AWS resources, grab the IP, check it, and then destroy them. This gives you 100% confidence that your code works on a fresh deployment.
4. Policy as Code: Enforcing Guardrails with OPA
The Problem
tfsec checks for insecure code. But what about compliant code?
- "We only allow servers in
us-east-1." - "No one is allowed to spend more than $100 on a single resource."
- "All S3 buckets must have a 'Department' tag."
These aren't security bugs; they are Company Policies.
The Solution: Open Policy Agent (OPA)
OPA (pronounced "Oh-pa") is a general-purpose policy engine. We will use a tool called Conftest, which makes using OPA with Terraform very easy.
π οΈ Hands-On: Writing a Policy
Installation:
brew install conftest(or download binary)
The Workflow:
- Convert Terraform Plan to JSON (OPA loves JSON).
- Write a policy in a language called Rego.
- Check the JSON against the Rego.
Step 1: Generate JSON Plan
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.jsonStep 2: Write the Policy (policy/tags.rego)
Rego looks weird at first. Read this as: "Deny if the resource does not have a Department tag."
package main
deny[msg] {
# Find all resources in the plan
resource := input.resource_changes[_]
# specific to AWS instances
resource.type == "aws_instance"
# Check if tags exist
tags := resource.change.after.tags
# Check if "Department" tag is missing
not tags.Department
msg := sprintf("Resource %v is missing the 'Department' tag!", [resource.address])
}Step 3: Run the Test
conftest test tfplan.json -p policy/The Output:
FAIL - tfplan.json - Resource aws_instance.web is missing the 'Department' tag!If you see this in your CI/CD pipeline, the build stops. You have successfully enforced company policy without being the "bad guy" in the meeting. The robot was the bad guy.
Summary Checklist π
Before you call your Terraform code "Production Ready," ask these questions:
- Security: Did
tfsecpass? (No open ports, no public buckets). - Cost: Did
infracostshow a reasonable bill? - Functionality: Did
Terratestactually spin it up and verify it works? - Compliance: Did
OPA/Conftestallow the configuration based on company rules?
π References & Documentation
- Tfsec Documentation
- Infracost Setup Guide
- Terratest Quick Start
- OPA/Conftest Examples
- Rego Playground (Great for practicing policy logic)
Challenge
You are a DevOps engineer responsible for implementing infrastructure guardrails using Open Policy Agent (OPA). Your company has mandated several new compliance policies for all aws_instance resources deployed via Terraform.
Your task is to write a single OPA policy in the Rego language that enforces the following four rules against a Terraform JSON plan file.
Compliance Rules:
- Mandatory Tagging: Every
aws_instancemust have aDepartmenttag. The tag's value does not matter, but the key must be present. - Disallowed Instance Types: To prevent accidental use of underpowered machines, the
t2.microandt2.nanoinstance types are strictly forbidden. - Approved AMI: All instances must be launched from the company's official hardened AMI, which has the ID
ami-0c55b159cbfafe1f0. - No Public IPs: For security reasons, no
aws_instanceshould have a public IP address enabled. Theassociate_public_ip_addressattribute must evaluate tofalse.
Expected result
Your solution should be a single, valid Rego policy file that correctly implements all four compliance rules by completing the logic inside each deny block.
A correct solution will fulfill the following requirements:
- Rule 1 (Tagging): The logic correctly checks for the absence of the
Departmentkey within theinstance.change.after.tagsobject. A common way to implement this isnot instance.change.after.tags.Department. - Rule 2 (Instance Type): The logic correctly checks if
instance.change.after.instance_typeis a member of thedisallowed_typesset. - Rule 3 (AMI): The logic compares
instance.change.after.amiwith theapproved_amistring and triggers a denial if they do not match. - Rule 4 (Public IP): The logic correctly checks if
instance.change.after.associate_public_ip_addressis explicitly set totrue. It must handle cases where the key is absent, as that is a valid (non-public) configuration.
An example of a complete, correct implementation for Rule 4 would be:
deny[msg] {
instance := aws_instances[_]
instance.change.after.associate_public_ip_address == true
msg := sprintf("Instance '%s' must not have a public IP.", [instance.address])
}