Overview and What You Will Learn
A Terraform module is a folder of .tf files that does one job well, such as creating a secure S3 bucket or an ECS service, and exposes a small set of inputs and outputs. Callers use it without reading its internals, and the logic lives in exactly one place. That means a security fix is made once and rolled out by bumping a version.
Without modules, five teams that each need a bucket with versioning, encryption, and a public access block end up with five near-identical resource blocks. When an audit finds one copy missing the public access block, nobody knows how many other copies share the bug.
In this lab you will:
- Lay out a module the way the Terraform Registry and tooling expect
- Pin provider requirements with flexible version constraints
- Write input variables with types, defaults, descriptions, and validation
- Decide what to hardcode, what to expose as inputs, and what to expose as outputs
- Call the module from a root configuration and chain its outputs
- Test the module and release it with Git tags
- Generate README documentation automatically
Why This Matters in Production
Imagine a platform team at a company like Razorpay or Shopify that publishes one ECS service module used by dozens of microservice repositories. Every service inherits the same CPU limits, log driver, and health check defaults. When a compliance rule later requires extra logging, the team ships one new major version, and each service team adopts it by changing a single ref in its module block, on its own schedule.
That is the economic case for modules: the cost of writing one is paid once, while the cost of copy-pasting compounds every time someone slightly breaks the pattern.
Core Principles
A module takes inputs through variables, creates resources, and returns outputs. The caller sees only the two ends of that pipeline.
The standard file layout looks like this, and tools such as terraform-docs assume these names:
modules/s3-secure-bucket/ main.tf variables.tf outputs.tf versions.tf README.md examples/ basic/ main.tf tests/ validation.tftest.hclFour rules shape a good module:
- One job per module:
vpc,iam-role, andrds-postgrescompose better than one giantnetworkingmodule. - Hardcode non-negotiable policy: If public buckets are never allowed, do not add a flag for it.
- Validate inputs early: A clear validation message beats a confusing cloud API error later.
- Expose only what callers need: Every output is a contract you must maintain.
Detailed Step-by-Step Practical Lab
How to Create the Standard Module Directory Structure
A consistent skeleton makes a module familiar to every engineer and compatible with registry tooling. Start with these files even for a small module.
mkdir -p modules/s3-secure-bucket/examples/basic modules/s3-secure-bucket/testscd modules/s3-secure-bucket touch main.tf variables.tf outputs.tf versions.tf README.mdtouch examples/basic/main.tf tests/validation.tftest.hclHow to Declare Provider and Terraform Version Requirements in a Module
A module should declare what it needs with loose constraints, because the root configuration controls the exact provider version. Never put a provider block inside a reusable module.
terraform { required_version = ">= 1.7.0" required_providers { aws = { source = "hashicorp/aws" # Lower bound only: the root module decides the exact version version = ">= 5.0" } }}TipA root configuration pins tightly (for example
version = "5.31.0"), while a module states the minimum it was tested against. A tight pin inside a module blocks consumers who use a different provider version.
How to Write Input Variables With Validation
Good variables have a type, a description, a safe default where one exists, and a validation block for any value with real-world rules. S3 names, for instance, are 3 to 63 characters, lowercase, and must start and end with a letter or number.
# variables.tfvariable "bucket_name" { description = "Globally unique S3 bucket name: 3-63 characters, lowercase letters, numbers, dots, hyphens." type = string validation { condition = can(regex("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$", var.bucket_name)) error_message = "bucket_name must be 3-63 characters of lowercase letters, numbers, dots, or hyphens, starting and ending with a letter or number." }} variable "environment" { description = "Deployment environment, used for tagging." type = string validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "environment must be one of: dev, staging, prod." }} variable "enable_versioning" { description = "Whether to enable S3 versioning. Keep true for prod." type = bool default = true} variable "tags" { description = "Additional tags merged with the module's default tags." type = map(string) default = {}}How to Write the Module's Resources
The resources use the name this because the module name already describes the purpose. Security rules that must never change are hardcoded rather than exposed as variables.
# main.tflocals { common_tags = merge( var.tags, { ManagedBy = "terraform" Module = "s3-secure-bucket" Environment = var.environment } )} resource "aws_s3_bucket" "this" { bucket = var.bucket_name tags = local.common_tags} resource "aws_s3_bucket_versioning" "this" { bucket = aws_s3_bucket.this.id versioning_configuration { status = var.enable_versioning ? "Enabled" : "Suspended" }} resource "aws_s3_bucket_server_side_encryption_configuration" "this" { bucket = aws_s3_bucket.this.id rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } }} resource "aws_s3_bucket_public_access_block" "this" { bucket = aws_s3_bucket.this.id # Hardcoded on purpose: this module never creates a public bucket block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true}SecurityNotice that the public access block has no variable. If company policy is "no public S3 buckets", baking it into the module means nobody can switch it off by accident.
How to Decide What a Module Should Output
Output the values callers need to connect other resources, and keep internals private. Every output adds surface area you must keep stable across versions.
# outputs.tfoutput "bucket_id" { description = "The name of the created S3 bucket." value = aws_s3_bucket.this.id} output "bucket_arn" { description = "The ARN of the bucket, for use in IAM policies." value = aws_s3_bucket.this.arn} output "bucket_regional_domain_name" { description = "The regional domain name, useful as a CloudFront origin." value = aws_s3_bucket.this.bucket_regional_domain_name}How to Call a Module and Use Its Outputs
You call a module with a module block, pass inputs as arguments, and read results as module.<name>.<output>. Use a local path while developing.
# environments/prod/main.tfmodule "customer_uploads_bucket" { source = "../../modules/s3-secure-bucket" bucket_name = "devops-customer-uploads-prod" environment = "prod" enable_versioning = true tags = { Team = "platform" CostCenter = "infra-2026" }} resource "aws_iam_policy" "uploads_read" { name = "uploads-read-policy" policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Action = ["s3:GetObject"] Resource = "${module.customer_uploads_bucket.bucket_arn}/*" }] })}How to Test a Terraform Module
You test a module by validating it, planning an example, and using native terraform test for validation rules. Native tests need Terraform 1.6 or later, and mock_provider needs 1.7 or later.
# Format, initialise, and validate the exampleterraform fmt -check -recursivecd examples/basicterraform initterraform validateterraform plan# tests/validation.tftest.hclmock_provider "aws" {} run "rejects_invalid_bucket_name" { command = plan variables { bucket_name = "Bad_Name" environment = "dev" } expect_failures = [var.bucket_name]} run "accepts_valid_inputs" { command = plan variables { bucket_name = "devops-test-bucket-dev" environment = "dev" }}# Run the module's tests from the module directoryterraform testHow to Version and Release a Terraform Module With Git Tags
Tag each release with a semantic version, and consumers pin a ref so upgrades happen only when they choose. Increment the major version for breaking changes such as renamed variables or removed outputs.
git add .git commit -m "Initial release of s3-secure-bucket module"git tag v1.0.0git push origin main v1.0.0module "customer_uploads_bucket" { source = "git::https://github.com/devops-network/tf-modules.git//s3-secure-bucket?ref=v1.0.0" bucket_name = "devops-customer-uploads-prod" environment = "prod"}To adopt a new release, the consumer changes ref=v1.0.0 to the new tag and runs terraform init -upgrade, then reviews the plan.
How to Generate Module Documentation Automatically
terraform-docs builds the inputs and outputs tables from your code, so the README never drifts from the module. Add start and end markers to the README once, then regenerate on every change.
# README.md must contain these two marker lines where the tables belong:# <!-- BEGIN_TF_DOCS --># <!-- END_TF_DOCS --> terraform-docs markdown table --output-file README.md --output-mode inject .A good README also contains a short description, a usage example, and a link to examples/basic.
Production Best Practices & Common Pitfalls
- Name resources
this:aws_s3_bucket.thisreads better than repeating the module's purpose in every address. - Keep each module focused: Small modules compose cleanly, while a giant one is hard to version.
- Include an
examples/folder: It is the fastest way to learn the module and doubles as an integration test. - Validate inputs with clear errors: Do it for names, CIDR blocks, and enumerated values.
- Hardcode security policy: Do not offer flags for settings that must never change.
- Use
movedblocks when refactoring: Moving existing resources into a module without them makes Terraform destroy and recreate the resources. - Version with semantic tags: Never let consumers track
main. - Do not define providers inside modules: Let the root configuration configure them.
RememberA pinned
refmeans a module fix reaches consumers only when they bump the version. Announce releases and keep a changelog so teams know what changed.
Common MistakeMoving resources into a new module without
movedblocks. Terraform sees new addresses, plans to destroy the old resources, and recreates them, which can delete data.
Quick Reference & Troubleshooting Commands
| File | Purpose |
|---|---|
main.tf |
The resource blocks the module creates |
variables.tf |
Every input, with type and validation |
outputs.tf |
Every value exposed to the caller |
versions.tf |
Terraform and provider requirements |
README.md |
Usage, inputs, and outputs |
| Command | Description |
|---|---|
terraform fmt -recursive |
Format all files |
terraform validate |
Check syntax and references |
terraform test |
Run native module tests |
terraform init -upgrade |
Fetch a newer module version or provider |
| Error | Root cause | Fix |
|---|---|---|
Unsupported argument |
Variable not declared in the module | Check the exact name in variables.tf |
Required variable not set |
Variable has no default | Pass it in the module block |
| Custom validation message at plan | Input failed a validation rule |
Read the message and correct the value |
| Module edits not picked up | Pinned ref instead of a local path |
Use a local source while developing, then retag |