Chapter 6 of 24

Variables, Contracts, and Modules

Small inputs and explicit outputs make infrastructure composition reviewable.

Learning objectives

Contracts before reuse

Variable validation

Reject invalid caller input before provider work begins.

Preconditions and postconditions

Guard assumptions before an action or a resulting attribute after it.

Checks

Report a continuous health expectation without changing ownership.

Outputs

Publish only values a caller needs, not a provider-object dump.

Keep a module around a coherent lifecycle and contract. A module that forwards every argument to one resource adds a second place to debug with no new boundary.

AWS context

A VPC, an EKS cluster, and application data have different blast radii. Give each a small input contract and expose stable IDs or ARNs. Put IAM policy and account assumptions at the caller boundary where reviewers can see them.

Lab: a naming contract

Open labs/06-modules/main.tf and the typed module input. One object carries related application and environment values.

cd learn-terraform/labs/06-modules
terraform init -backend=false
terraform validate
terraform plan

tofu init -backend=false
tofu validate
tofu plan

The module emits course-learning. Change the environment to any other value to see validation fail before an AWS provider is involved.

Review a module call

ReviewExpected
Input shapeEvery field has a type, description, and domain check where needed.
OutputA stable caller-facing value, not an entire provider object.
SizeOne lifecycle boundary, not a resource wrapper.

Failure drill

Do not fix a validation error by weakening the type. Correct the caller value or make the intended domain explicit. A permissive any hides a contract breach until a provider plan is harder to read.

Verify

  1. Run both explicit CLI command sets with a supported version.
  2. Confirm name_prefix is course-learning.
  3. Deliberately use an invalid environment and read the variable error.

Cleanup

This lab has no provider resources. Remove only a generated .terraform directory; do not commit it.

Quick check

When is a precondition better than validation?

When the rule depends on a planned resource or another input rather than one variable.

Should every resource become a module?

No. Extract only a reusable lifecycle and contract.

Recap and next

Module quality comes from a clear boundary, not from the number of files. Next, select environment inputs and exercise them with native tests.

Next: Environments, Testing, and Debugging