Terraform Modules Tutorial

Terraform Modules Tutorial

Introduction

Every Terraform user reaches the same moment. The first project is a single main.tf that creates a virtual machine, and it works. The second project copies that file and changes a few values. By the fifth copy, the files have drifted apart: one has the security fix, another does not, and nobody remembers which copy is the correct one. That is the problem Terraform modules solve.

A module is a reusable package of Terraform configuration — a folder of .tf files with a defined set of inputs and outputs — that you can call from many projects. Instead of copying a block of resources, you call the module, pass in the values that differ, and let the module handle the rest. The result is infrastructure that is consistent, reviewable and far easier to change: fix a bug once, in the module, and every project that uses it gets the fix.

This tutorial teaches modules from zero: what they are and why they exist, how to write your first module, how to use one from a local folder, Git or the public Terraform Registry, how versioning works, and how to compose modules into a root module that builds a real stack — a VPC, an EC2 instance and an S3 bucket. It assumes you can already write a basic Terraform configuration and run terraform init, plan and apply. If that is new to you, start with our Terraform Tutorial for Beginners first.

Version note (28 Nov 2026): the current Terraform release is 1.17.2, released 11 November 2026. All HCL in this tutorial is valid for Terraform 1.17 and follows the syntax in the HashiCorp documentation. The AWS examples use the AWS provider; resource argument names were checked against the Terraform Registry provider documentation.

What Terraform Modules Are — and Why They Exist

A module is a directory containing Terraform configuration files. That is the whole definition — and it includes a fact beginners miss: the configuration you already write is a module too. The directory where you run terraform apply is called the root module. Every other module is a child module, called from the root module (or from another child module) with a module block.

module "web_bucket" {
  source = "./modules/s3-bucket"

  bucket_name = "my-app-assets"
  versioning  = true
}

The source tells Terraform where the module lives. The other arguments are input variables — values the caller passes in. Inside the module, resources use those variables instead of hard-coded values, and the module returns results through outputs that the caller can use.

Modules exist for three reasons. The first is reuse: write the S3 bucket configuration once — with versioning, encryption and public access blocked — and use it in every project instead of copying the resource block and hoping every copy is the same. The second is consistency: a module encodes your team’s standards, so a bucket created through the module is always encrypted and always versioned, because the module does not offer a way to create one that is not. The third is abstraction: a caller that writes module “vpc” with a CIDR block and a list of availability zones does not need to know how many subnets, route tables and gateways the module creates. The complexity is inside the module, where it can be tested and reviewed once.

What modules are not: they are not a deployment tool, and they do not manage state. State still belongs to the root module that calls them, and our Terraform State Explained guide covers how that works — including remote backends and locking, which matter as soon as more than one person applies the same configuration. Modules also do not version themselves: versioning comes from where the module is stored, which is the subject of the Registry section below.

Writing Your First Module — Variables, Outputs and Locals

A module has the same files as any Terraform configuration, conventionally split into three: main.tf for resources, variables.tf for inputs, and outputs.tf for results. A fourth file, versions.tf, pins the Terraform and provider versions the module needs. Start with a simple, genuinely useful module: an S3 bucket with versioning and encryption switched on.

The file layout

modules/s3-bucket/
  main.tf
  variables.tf
  outputs.tf
  versions.tf

variables.tf — the module’s inputs

variable "bucket_name" {
  description = "Globally unique name for the S3 bucket."
  type        = string
}

variable "versioning" {
  description = "Whether to enable versioning on the bucket."
  type        = bool
  default     = true
}

variable "tags" {
  description = "Tags to apply to the bucket."
  type        = map(string)
  default     = {}
}

Every variable needs a type and a description. The description is not decoration — it is the documentation a caller reads when deciding what to pass, and the Registry displays it on the module’s page. A default makes a variable optional; a variable with no default is required, and Terraform will refuse to plan until the caller provides it. Use that deliberately: bucket_name has no default because there is no sensible default for a globally unique name, while versioning defaults to true because that is the safe choice.

Add validation blocks for values that have rules. A bucket name, for example, must be lowercase:

variable "bucket_name" {
  description = "Globally unique name for the S3 bucket."
  type        = string

  validation {
    condition     = var.bucket_name == lower(var.bucket_name)
    error_message = "Bucket names must be lowercase."
  }
}

Validation catches mistakes at terraform plan time, with a message you wrote, instead of at apply time with an AWS error.

main.tf — the resources

resource "aws_s3_bucket" "this" {
  bucket = var.bucket_name
  tags   = var.tags
}

resource "aws_s3_bucket_versioning" "this" {
  bucket = aws_s3_bucket.this.id

  versioning_configuration {
    status = var.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

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

Three things to notice. First, since AWS provider version 4, bucket settings such as versioning and encryption live in their own resources — aws_s3_bucket_versioning and aws_s3_bucket_server_side_encryption_configuration — not as blocks inside aws_s3_bucket. The inline versioning and server_side_encryption_configuration blocks inside aws_s3_bucket are deprecated; do not use them in new modules. Second, resources inside a module refer to each other by their local names (aws_s3_bucket.this.id), exactly as they would in a root module. Third, the ternary expression var.versioning ? “Enabled” : “Suspended” turns the boolean input into the string the AWS provider expects — a small pattern you will use constantly in modules.

outputs.tf — what the module returns

output "bucket_id" {
  description = "The name (ID) of the bucket."
  value       = aws_s3_bucket.this.id
}

output "bucket_arn" {
  description = "The ARN of the bucket."
  value       = aws_s3_bucket.this.arn
}

Outputs are how a caller gets information back out of a module — the bucket’s ARN, for example, so another module or resource can use it. Keep outputs to the values callers genuinely need: every output is part of the module’s public interface, and removing one later is a breaking change for everyone who uses it.

locals — values used only inside the module

locals hold values that are computed inside the module and never exposed to the caller. Use them for a name built from several inputs, or a value derived from a variable:

locals {
  name_prefix = "app-${var.environment}"
}

resource "aws_s3_bucket" "this" {
  bucket = "${local.name_prefix}-${var.bucket_name}"
  tags   = var.tags
}

The rule of thumb: a value the caller supplies is a variable; a value the caller needs back is an output; a value only the module itself needs is a local. Keeping those three separate is what makes a module readable six months later.

versions.tf — what the module needs

terraform {
  required_version = ">= 1.10.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

A required_version constraint in the module protects callers from running it with a Terraform version it was never tested against. Note that a module’s required_providers block only declares which providers it needs — the provider configuration itself (region, credentials) lives in the root module, never in a child module. A child module that configures its own provider is a common beginner mistake, and Terraform will refuse it in most cases.

Using a Module — Source Paths, Inputs and Version Constraints

Calling a module is a module block in the root module. The source argument is the only required one; everything else is an input variable.

Local modules

module "assets" {
  source = "./modules/s3-bucket"

  bucket_name = "my-app-assets-2026"
  versioning  = true

  tags = {
    Environment = "production"
    Team        = "platform"
  }
}

A local source is a relative path from the root module directory. Local modules are the right choice while you are developing a module, and for modules that belong to one project and will never be shared. Their limitation is exactly that: they cannot be shared between repositories, and they have no versioning — the caller always gets whatever is in the folder right now.

Remote modules: Git and the Registry

A module can also live in a Git repository. Terraform supports Git URLs as sources, with a ?ref= query to pin a branch, tag or commit:

module "vpc" {
  source = "git::https://github.com/example-org/terraform-modules.git//modules/vpc?ref=v1.2.0"
}

The double slash (//) separates the repository URL from the path inside the repository. The ?ref=v1.2.0 pins the module to a tag — without it, Terraform uses the repository’s default branch, which means your infrastructure can change the next time someone pushes to it. Always pin a ref on a Git source.

Registry modules use a shorter address — namespace/name/provider — and a separate version argument:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = "app-vpc"
  cidr = "10.0.0.0/16"
}

The version argument only works with Registry sources; it is not allowed on local or Git sources, where the version comes from the ref or the folder contents. After adding or changing a module source, run terraform init so Terraform downloads it into the .terraform directory, then terraform plan to see what it will create.

Version constraints and the ~> operator

Version constraints use the same operators as provider requirements. The one to learn first is ~>, the pessimistic constraint operator:

ConstraintAllows
= 5.0.0Exactly 5.0.0
~> 5.05.0 and above, below 6.0
~> 5.1.05.1.0 and above, below 5.2.0
>= 5.0, < 6.0Any 5.x release

~> 5.0 is the usual choice for a module you trust: it takes patch and minor updates, which should be backward compatible, but never crosses into the next major version, where breaking changes are allowed. The difference between ~> 5.0 and ~> 5.1.0 is the number of version components: with two components, the constraint allows minor changes; with three, it allows only patch changes. Pin major versions in production, and let patches flow. When you upgrade a module to a new major version, read its changelog first — the breaking changes are the reason the major version exists.

Use the module’s outputs like any other value, with the module.<name>.<output> address:

resource "aws_s3_bucket_policy" "assets" {
  bucket = module.assets.bucket_id
  policy = data.aws_iam_policy_document.assets.json
}

The Public Terraform Registry and Semantic Versioning

The Terraform Registry is the public index of providers and modules. Anyone can publish a module; the ones that matter are the verified ones, marked with a badge, published by HashiCorp partners or well-known community organisations. Before using a Registry module, check three things on its page: the latest version and when it was published, the inputs and outputs documentation, and the source repository link — a module whose repository has no recent activity is a module nobody is maintaining.

Registry modules follow semantic versioning: a version number MAJOR.MINOR.PATCH, where a major bump means breaking changes, a minor bump means new features that are backward compatible, and a patch bump means bug fixes. That convention is what makes ~> constraints work — ~> 5.0 is safe to allow precisely because a 5.x release promises not to break your configuration. A module that does not follow semantic versioning cannot be trusted with a loose constraint, so pin it exactly (= 1.4.2) until its maintainers demonstrate otherwise.

The Registry also enforces a rule that trips up beginners: a Registry module’s source address has three parts, namespace/name/provider — for example, terraform-aws-modules/vpc/aws. The provider at the end is the provider the module is written for, not the cloud you happen to use. A module written for AWS cannot be used on Azure by changing the provider; it has to be rewritten, because the resources inside it are AWS resources.

Do not treat the Registry as a shortcut around understanding what a module does. Read the module’s source before you use it in production — every Registry page links to it. Check what resources it creates, what defaults it sets, and whether it creates anything you did not expect, such as a NAT gateway that bills by the hour. A module you have not read is a configuration you have not reviewed.

Composing Modules — A VPC, an EC2 Instance and an S3 Bucket

A root module is where modules come together. Here is a small but real stack: a VPC module, an EC2 instance that runs in it, and the S3 bucket module from earlier. The point of the example is not the individual resources — it is how the modules connect: the VPC module’s outputs become the EC2 module’s inputs.

terraform {
  required_version = ">= 1.10.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = "app-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["eu-west-2a", "eu-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true
}

module "assets" {
  source = "./modules/s3-bucket"

  bucket_name = "my-app-assets-2026"
  versioning  = true

  tags = {
    Environment = "production"
  }
}

resource "aws_security_group" "web" {
  name   = "web-sg"
  vpc_id = module.vpc.vpc_id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "web" {
  ami                    = var.ami_id
  instance_type          = "t3.micro"
  subnet_id              = module.vpc.public_subnets[0]
  vpc_security_group_ids = [aws_security_group.web.id]

  tags = {
    Name = "web-server"
  }
}

The VPC module is the only part taken from the Registry here — it is the canonical example of a module worth reusing, because a correct VPC needs subnets, route tables, gateways and NAT, and getting any of those wrong is expensive. The version = “~> 5.0” constraint is an example: check the Registry page for the current major line before you copy it. The EC2 instance and the security group are plain resources in the root module, not modules of their own — a single instance does not need a module, and wrapping one resource in a module adds indirection without adding value.

Notice how the pieces connect through outputs: module.vpc.vpc_id feeds the security group, module.vpc.public_subnets[0] places the instance in the VPC’s first public subnet. That is composition — modules passing values to each other through the root module — and it is the pattern that scales: add a database module next, pass it module.vpc.private_subnets, and the stack grows without any module needing to know about the others.

Two things to check before you apply a stack like this. First, enable_nat_gateway creates a NAT gateway, which is a billed AWS resource — single_nat_gateway = true keeps it to one gateway instead of one per availability zone, which is the right trade-off for a learning environment. Second, the state for this stack lives wherever the root module’s backend points. Our Terraform State Explained guide covers remote backends: for a shared stack, store state in an S3 bucket with versioning and native locking switched on (use_lockfile = true), which is available from Terraform 1.10 and generally available since 1.11. Do not say a DynamoDB table is required for locking — the DynamoDB locking arguments are deprecated in favour of the S3 native lock file.

Testing Modules, and the Mistakes to Avoid

Modules need testing, because a bug in a module is a bug in every project that uses it. The cheapest tests are the ones you already know: terraform fmt to check formatting, terraform validate to check syntax and internal consistency, and terraform plan against a test root module that calls the module with realistic inputs:

terraform fmt -recursive
terraform validate
terraform plan -refresh-only

terraform plan -refresh-only updates the state to match real infrastructure without proposing changes — it is the safe way to check for drift. Note that the standalone terraform refresh command is deprecated: it writes state changes without showing you a plan first, and HashiCorp recommends -refresh-only on plan and apply instead. For deeper testing, Terratest is the standard tool: it writes tests in Go that apply a module, check the real resources, and destroy them afterwards. It is worth knowing the name; for a first module, validate and a plan against a test configuration are enough.

The mistakes to avoid:

  • Too many inputs. A module with thirty variables is not reusable — it is a resource block with extra steps. If a value is the same in every use, hard-code it inside the module or derive it in a local.
  • Too few inputs. The opposite failure: a module that hard-codes the environment name, the region or the instance type cannot be used anywhere else. Parameterise what genuinely varies between callers.
  • Leaking implementation details. Callers should use module.vpc.vpc_id, not reach into the module’s resources. Outputs are the interface; everything else is internal.
  • No version pinning. A Registry module without a version constraint takes the latest release on the next terraform init, which may be a major version with breaking changes. Pin it.
  • Secrets as variables. Never pass a password or a key as a plain variable with a default value, and never commit a .tfvars file containing one. Use your cloud’s secret store or a variable marked sensitive = true, and keep the value out of version control.
  • One giant module. A module that creates a VPC, a database, a load balancer and an application is not a module — it is a whole environment pretending to be a component. Split it, and let the root module compose the pieces.

FAQ

What is the difference between a module and a resource?

A resource is a single piece of infrastructure — one S3 bucket, one EC2 instance. A module is a package of configuration that can contain many resources, plus variables, outputs and locals. You call a module; Terraform creates the resources inside it.

Can I use a module without the Registry?

Yes. Local modules (source = “./modules/s3-bucket”) and Git sources work without the Registry at all. The Registry is a place to discover and version published modules — it is not required to use modules.

What does ~> 5.0 mean?

It is a pessimistic version constraint: allow version 5.0 and above, but below 6.0. Patch and minor updates are allowed; a major version bump, which may contain breaking changes, is not. ~> 5.1.0 is stricter — it allows only patch updates below 5.2.0.

Should every resource be in a module?

No. A resource used once, in one place, belongs in the root module. Make a module when the same configuration is needed in more than one place, or when it encodes a standard — like an encrypted, versioned S3 bucket — that should be applied consistently.

How do I update a module to a new version?

Change the version constraint (or the Git ?ref=), run terraform init -upgrade, and run terraform plan to see what changes. Read the module’s changelog first for a major version bump, and apply in a non-production environment before production.

Conclusion

Modules are the point where Terraform stops being a way to write infrastructure and starts being a way to manage it. A root module full of copied resource blocks works until the second project; a library of small, well-tested modules — a bucket, a VPC, a database — works for the tenth. The discipline is simple: variables for what varies, outputs for what callers need, locals for everything else, a version pin on every Registry module, and a test configuration that proves the module does what it claims.

Start with the S3 bucket module in this tutorial. Use it in a real project, notice what you want to change, and change it once — in the module. Then read the next module you use from the Registry the way you would read a colleague’s code, because that is what it is. And when you are ready for the patterns that build on modules — workspaces, remote state and team workflows — our Terraform State Explained guide is the next step, and our Terraform Interview Questions cover the module questions interviewers actually ask.

Sources checked 28 Nov 2026: Terraform 1.17.2 release (GitHub hashicorp/terraform releases — 1.17.2, 11 November 2026; 1.17.0, 21 October 2026); HashiCorp Terraform documentation (developer.hashicorp.com — terraform refresh is deprecated, use plan -refresh-only / apply -refresh-only; S3 backend native locking with use_lockfile = true, introduced in Terraform 1.10 and generally available in 1.11, with the DynamoDB locking arguments deprecated); Terraform Registry provider documentation (registry.terraform.io — aws_s3_bucket_versioning and aws_s3_bucket_server_side_encryption_configuration as separate resources since AWS provider 4, inline versioning and server_side_encryption_configuration blocks deprecated). External references: Terraform language documentation — Modules · Terraform Registry.

—

Scroll to Top