What is a Child Module in Terraform: Explanation and Example
child module in Terraform is a reusable set of configuration files stored in a separate folder or repository that you call from a root module. It helps organize and share infrastructure code by breaking it into smaller, manageable parts.How It Works
Think of Terraform modules like building blocks for your infrastructure. A child module is one of these blocks stored separately, which you can include inside your main configuration, called the root module. This is similar to how you might use a recipe book: the root module is your main recipe, and child modules are smaller recipes you reuse to make parts of the dish.
When you call a child module, Terraform loads its configuration and resources as part of your overall setup. This lets you avoid repeating the same code and keeps your infrastructure organized, just like using pre-made ingredients saves time and effort in cooking.
Example
This example shows a root module calling a child module that creates an AWS S3 bucket. The child module is stored in a folder named modules/s3_bucket.
/* Root module main.tf */ module "my_bucket" { source = "./modules/s3_bucket" bucket_name = "my-unique-bucket-123" } /* Child module modules/s3_bucket/main.tf */ resource "aws_s3_bucket" "bucket" { bucket = var.bucket_name acl = "private" } /* Child module modules/s3_bucket/variables.tf */ variable "bucket_name" { type = string }
When to Use
Use child modules when you want to reuse the same infrastructure setup in multiple places or projects. For example, if you need to create similar storage buckets, virtual machines, or networks repeatedly, child modules save time and reduce mistakes.
They also help teams work together by sharing tested modules, making infrastructure easier to manage and update. If your project grows complex, breaking it into child modules keeps your code clean and understandable.
Key Points
- Child modules are reusable Terraform configurations stored separately.
- They help organize and simplify infrastructure code.
- Called from a root module using the
moduleblock with asourcepath. - Useful for sharing and reusing common infrastructure patterns.