Learn Terraform Β· 11/11

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:

hcl
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:

bash
tfsec .

The Output:
You will see a beautiful (and terrifying) list of failures.

text
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:

hcl
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 tfsec or Checkov are 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).

bash
infracost register

The Scenario:
Let's see how much a "cheap" server costs. Create main.tf:

hcl
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:

bash
infracost breakdown --path .

The Output:

text
 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.17

Industry 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:

  1. Install Go: brew install go (or download from golang.org)
  2. Create a folder test inside your project.

The Workflow:

  1. Init: Terraform Init/Apply.
  2. Validate: Run code to check infrastructure (HTTP request, SSH command).
  3. Teardown: Terraform Destroy (ALWAYS happens, even if test fails).

The Code (test/terraform_basic_test.go):

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:

bash
cd test
go test -v

What 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:

  1. Convert Terraform Plan to JSON (OPA loves JSON).
  2. Write a policy in a language called Rego.
  3. Check the JSON against the Rego.

Step 1: Generate JSON Plan

bash
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json

Step 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."

rego
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

bash
conftest test tfplan.json -p policy/

The Output:

text
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:

  1. Security: Did tfsec pass? (No open ports, no public buckets).
  2. Cost: Did infracost show a reasonable bill?
  3. Functionality: Did Terratest actually spin it up and verify it works?
  4. Compliance: Did OPA/Conftest allow the configuration based on company rules?

πŸ“š References & Documentation

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:

  1. Mandatory Tagging: Every aws_instance must have a Department tag. The tag's value does not matter, but the key must be present.
  2. Disallowed Instance Types: To prevent accidental use of underpowered machines, the t2.micro and t2.nano instance types are strictly forbidden.
  3. Approved AMI: All instances must be launched from the company's official hardened AMI, which has the ID ami-0c55b159cbfafe1f0.
  4. No Public IPs: For security reasons, no aws_instance should have a public IP address enabled. The associate_public_ip_address attribute must evaluate to false.

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 Department key within the instance.change.after.tags object. A common way to implement this is not instance.change.after.tags.Department.
  • Rule 2 (Instance Type): The logic correctly checks if instance.change.after.instance_type is a member of the disallowed_types set.
  • Rule 3 (AMI): The logic compares instance.change.after.ami with the approved_ami string and triggers a denial if they do not match.
  • Rule 4 (Public IP): The logic correctly checks if instance.change.after.associate_public_ip_address is explicitly set to true. 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:

rego
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])
}
rego

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.