Write First Terraform Module: Step-by-Step Tutorial

If you have spent any time with Terraform, you have probably copied resource blocks from one project to another. Learning to write first Terraform module code of your own is how you stop copying and start reusing. A module is just a folder of .tf files that bundles resources, variables, and outputs into one unit any configuration can call.

This terraform module tutorial walks you through a real, working example: an S3 bucket module. You will create the three files every module needs, call the module from a root configuration, version it with Git tags, and test it with terraform plan before anything touches your cloud account. No prior module experience required.

What a Terraform Module Actually Is

Technically, every Terraform configuration is already a module. The .tf files in your working directory form the root module. A child module is the same idea moved into its own folder, so other configurations can reference it instead of duplicating the code.

The payoff is consistency. When five projects each need an S3 bucket with versioning, encryption, and a standard naming scheme, a shared module means one place to fix a misconfiguration instead of five. That single source of truth is the whole reason modules exist.

Write First Terraform Module: The Three Files

A minimal module follows a predictable terraform module structure. Create this layout inside your project:

modules/
└── s3-bucket/
    ├── main.tf
    ├── variables.tf
    └── outputs.tf

Each file has one job:

  • main.tf — the resources the module creates. This is the actual infrastructure.
  • variables.tf — the inputs the caller provides. Anything that changes between environments (bucket name, tags, region) belongs here, never hardcoded in main.tf.
  • outputs.tf — the values the module hands back to the caller, like the bucket ARN.

Building a Reusable Terraform Module: An S3 Example

Start with variables.tf. Typed variables with descriptions catch mistakes early and document the module for the next person who uses it:

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

variable "environment" {
  description = "Deployment environment, used in tags."
  type        = string
  default     = "dev"
}

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

Next, main.tf creates the bucket with versioning and encryption turned on:

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

  tags = merge(
    {
      Environment = var.environment
      ManagedBy   = "terraform"
    },
    var.tags
  )
}

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

  versioning_configuration {
    status = "Enabled"
  }
}

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"
    }
  }
}

Finally, outputs.tf exposes what callers need:

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

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

That is the complete module. Three files, one reusable Terraform module you can now drop into any project.

Calling Your Module from a Root Configuration

Back in your root configuration, a module block points at the folder and passes values for the variables:

module "app_bucket" {
  source      = "./modules/s3-bucket"
  bucket_name = "my-app-assets-2026"
  environment = "prod"

  tags = {
    Team = "platform"
  }
}

output "bucket_arn" {
  value = module.app_bucket.bucket_arn
}

Notice how the caller reads the module’s output as module.app_bucket.bucket_arn. The source argument also accepts a Git URL or a Terraform Registry address, which is what you will use once the module is shared. For remote sources, always pin to a version: source = "git::https://github.com/your-org/terraform-s3-bucket.git?ref=v1.0.0".

Versioning Your Module

The moment a second team uses your module, changing its inputs or outputs can break their code. Versioning solves that. For a Git-hosted module, tag releases with semantic versioning:

git tag v1.0.0
git push origin v1.0.0

Follow three rules and versioning stays painless:

  • Major versions (v2.0.0) may break the interface: renamed variables, removed outputs.
  • Minor versions (v1.1.0) add features without breaking existing callers.
  • Patch versions (v1.0.1) fix bugs only.

Keep a short CHANGELOG.md in the module repository so callers can see what changed before they upgrade. If you publish to the Terraform Registry, the registry reads your Git tags automatically.

Testing with terraform plan and terraform validate

Before any real infrastructure is created, run the standard checks from the root configuration:

terraform init
terraform fmt -check -recursive
terraform validate
terraform plan

terraform validate catches syntax and type errors without touching the cloud. terraform plan shows exactly which resources the module will create, which is where you confirm that variables flow through correctly. Run plan against a sandbox account first; only promote the module to production use after the plan output looks right.

A useful habit: keep an examples/complete folder in the module repository with a small root configuration that calls the module. It doubles as documentation and as a smoke test you can plan on every change.

Best Practices for Your First Module

  • One module, one job. A module that creates a bucket, a database, and a DNS record is three modules pretending to be one.
  • Expose inputs, hide internals. Callers should set variables, not read your resource blocks.
  • Never hardcode account-specific values. Account IDs, regions, and naming prefixes belong in variables.
  • Pin provider versions with a required_providers block so the module behaves the same everywhere.
  • Document every variable and output with a description. Future you will thank present you.

FAQ

Do I need the Terraform Registry to share a module?

No. A Git repository URL works as a module source, including private repositories with the right credentials. The registry adds discoverability and version browsing, which matters for public or company-wide modules.

How is a module different from a Terraform workspace?

They solve different problems. Workspaces keep separate state files for the same configuration, usually per environment. Modules are reusable building blocks of configuration code. You will often use both: one module, deployed through workspaces for dev, staging, and prod.

Can a module call another module?

Yes. Modules nest freely: your S3 bucket module could be called by a higher-level “static website” module. Keep nesting shallow, though. More than two or three levels gets hard to trace.

When should I not write a module?

If the code is used exactly once and is specific to one project, a module adds indirection without benefit. Extract a module when you see the same pattern a second time, not the first.

Conclusion

You now have a working, versioned S3 module: three files, a clean interface of variables and outputs, and a test flow with terraform plan. The pattern scales. Your next module — a VPC, a database, a full application stack — follows the same shape: inputs in, resources in the middle, outputs out. Start small, version early, and let reuse compound.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.