⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Terraform & IaC Interview Questions Scenario 35 of 120 in Terraform & IaC
Senior DevOps / SRE [L2] Terraform Terraform Modules & State Production Scenario [L2]
🎯 Target Role / Context: Terraform Scenario #30 (L2) · Use VPC ID from another module

Q: How do you test Terraform modules?

To test Terraform modules, layer cheap static checks first, then plan-level assertions, then real apply tests in a disposable account.

#Terraform #L2 #IaC #Cloud Infrastructure
🎙️ Candidate Opening & Architectural Context
"To <strong>test Terraform modules</strong>, layer cheap static checks first, then plan-level assertions, then real apply tests in a disposable account. Use <code>terraform fmt</code>, <code>validate</code> and linters, then the native <code>terraform test</code> framework (Terraform 1.6 and later) with <code>.tftest.hcl</code> files, and reserve Terratest or full integration runs for behaviour you cannot assert from a plan. Interviewers ask this to see whether you treat infrastructure code like software: a test pyramid, safe cleanup, cost control and automation in CI. A strong answer explains what each layer catches and what it cannot."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's HashiCorp Certified Terraform Associate (003) Interactive Labs covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: To <strong>test Terraform modules</strong>, layer cheap static checks first, then plan-level assertions, then real apply tests in a disposable account. Use <code>terraform fmt</code>, <code>validate</code> and linters, then the native <code>terraform test</code> framework (Terraform 1.6 and later) with <code>.tftest.hcl</code> files, and reserve Terratest or full integration runs for behaviour you cannot assert from a plan. Interviewers ask this to see whether you treat infrastructure code like software: a test pyramid, safe cleanup, cost control and automation in CI. A strong answer explains what each layer catches and what it cannot.

1️⃣

Mental model: a test pyramid for Terraform modules

Cost and speed rise as you go from static checks to real infrastructure, so push most checks to the cheap layers.

  • Static: terraform fmt -check, terraform validate, TFLint rules and policy scanners such as Checkov or Trivy run in seconds without credentials.
  • Plan-level: terraform test with command = plan asserts planned values, conditions and variable validation without creating anything.
  • Apply-level: real apply in a sandbox account proves provider and API behaviour, outputs and idempotence, at the cost of time and money.
  • Consumer examples: keep an examples/ directory that uses the module like a caller would; tests and docs both use it.
  • Speed matters: static and plan tests finish in seconds to minutes, so developers actually run them locally before pushing.
2️⃣

Hands-on: test Terraform modules with terraform test

Native tests live next to the module and need no extra language or framework.

# tests/bucket.tftest.hcl
variables {
  name = "my-test-bucket"
}

run "plan_sets_expected_name" {
  command = plan
  assert {
    condition     = aws_s3_bucket.this.bucket == var.name
    error_message = "Bucket name must match input."
  }
}

run "rejects_uppercase_name" {
  command = plan
  variables { name = "BadName" }
  expect_failures = [var.name]
}

run "apply_creates_versioned_bucket" {
  command = apply
  assert {
    condition     = aws_s3_bucket_versioning.this.versioning_configuration[0].status == "Enabled"
    error_message = "Versioning must be enabled."
  }
}

# Run
# terraform init && terraform test
  • File layout: put *.tftest.hcl files in the module root or a tests/ directory and run terraform test.
  • run blocks: each run sets command (plan or apply), optional variables and one or more assert blocks.
  • Negative tests: use expect_failures to prove that variable validation rejects bad input.
  • Mocking: mock_provider (Terraform 1.7 and later) lets plan-style tests run without cloud credentials.
  • Run selectively: terraform test -filter=tests/bucket.tftest.hcl runs one file while you iterate, and -verbose prints plan output for debugging.
Advertisement
3️⃣

Integration testing with Terratest and CI

For multi-step scenarios and probing deployed endpoints, Go based Terratest is a common choice.

// test/vpc_test.go
func TestVpc(t *testing.T) {
  t.Parallel()
  opts := &terraform.Options{
    TerraformDir: "../examples/basic",
    Vars: map[string]interface{}{"name": "tt-" + random.UniqueId()},
  }
  defer terraform.Destroy(t, opts)
  terraform.InitAndApply(t, opts)
  vpcID := terraform.Output(t, opts, "vpc_id")
  assert.NotEmpty(t, vpcID)
}
  • Terratest: a Go test calls terraform.InitAndApply, reads outputs, makes real checks (HTTP, SDK calls) and destroys with defer.
  • Isolation: use unique name suffixes and a dedicated sandbox account so parallel CI runs do not collide.
  • CI tiers: run static and plan tests on every pull request; run apply-based tests on merge or nightly to control cost.
  • Cleanup guard: add a scheduled job that deletes leftover resources by tag, because failed runs can skip destroy.
4️⃣

Failure modes and what to verify

Tests can give false confidence if they only exercise the happy path or leave debris behind.

  • Plan cannot see runtime behaviour: values known only after apply cannot be asserted at plan stage; use an apply run for those.
  • Idempotence: follow an apply with plan -detailed-exitcode; exit code 2 means the module produces a perpetual diff.
  • Version matrix: test against the minimum and latest supported provider versions declared in the module required_providers.
  • Cost and secrets: keep sandbox accounts with budgets, short-lived OIDC credentials and no production data.
  • Cleanup behaviour: terraform test destroys infrastructure created by apply runs at the end, but a crashed job can still leave resources, so tag them.
  • Flaky tests: retry only known transient API errors; blindly retrying hides genuine ordering bugs in the module.
Pro Tip: A passing test suite that never destroys what it creates is just a slow resource leak; always verify teardown.
5️⃣

Policy and security testing for modules

Functional tests do not prove a module is safe, so add policy checks to the same pipeline.

  • Scanners: Checkov, Trivy or tfsec flag public buckets, open security groups and missing encryption directly in HCL.
  • Policy as code: run OPA/Conftest or Sentinel against terraform show -json tfplan to enforce organisation rules on planned changes.
  • Secure defaults: write tests that assert encryption, logging and versioning are on by default, so a refactor cannot quietly remove them.
  • Documentation tests: run terraform-docs in CI and fail if the README is stale, keeping the module contract visible.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Put most coverage into fast plan-level terraform test runs with mock providers and validation negative tests, and keep real-apply tests for a small set of scenarios in a sandbox account with tag-based cleanup."
⚡ 60-Second Elevator Pitch Talking Points
  • I test Terraform modules in layers: fmt, validate and linting, plan-based terraform test assertions, then apply tests in a sandbox.
  • I verify idempotence with a second plan using detailed-exitcode and verify outputs and behaviour with run assertions or Terratest.
  • I automate fast checks on every pull request, run apply tests on merge or nightly with OIDC credentials, and schedule tag-based cleanup.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Only running terraform validate Validate checks syntax and types, not provider behaviour or logic, so broken conditions and wrong defaults still pass.
  2. Running apply tests in a shared or production account Failed tests can leave or modify real resources and cost money; use a dedicated sandbox with budgets.
  3. Skipping the second plan after apply Without it you miss perpetual diffs caused by computed or normalised attributes.
  4. Testing against a single provider version Constraints allow a range, and a module can break on the minimum or newest version it claims to support.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →