What is a Module in Terraform: Definition and Usage
module in Terraform is a container for multiple resources that are used together. It helps organize and reuse infrastructure code by grouping related resources into a single unit.How It Works
Think of a Terraform module like a recipe in cooking. Instead of writing every step from scratch each time, you use a recipe that lists all ingredients and instructions. Similarly, a module groups related infrastructure resources, like servers and networks, into one reusable package.
When you use a module, Terraform reads its configuration and creates all the resources defined inside it. This makes managing complex setups easier because you can reuse the same module in different projects or parts of your infrastructure without rewriting code.
Example
This example shows a simple module that creates an AWS S3 bucket. The main Terraform file calls this module to create the bucket in your infrastructure.
/* Module: s3_bucket/main.tf */ resource "aws_s3_bucket" "bucket" { bucket = var.bucket_name acl = "private" } /* Module: s3_bucket/variables.tf */ variable "bucket_name" { type = string } /* Root configuration: main.tf */ module "my_bucket" { source = "./s3_bucket" bucket_name = "my-unique-bucket-12345" }
When to Use
Use modules when you want to organize your infrastructure code into smaller, manageable parts. They are helpful for:
- Reusing common infrastructure patterns across projects.
- Sharing configurations with your team to keep setups consistent.
- Reducing errors by avoiding repeated code.
- Making complex infrastructure easier to understand and maintain.
For example, if you often create similar virtual machines or networks, you can write a module once and use it everywhere.
Key Points
- Modules group related Terraform resources into reusable units.
- They help keep infrastructure code organized and DRY (Don't Repeat Yourself).
- Modules can be local folders or remote sources like GitHub.
- Using modules improves collaboration and consistency.