What is Root Module in Terraform: Simple Explanation and Example
root module is the main folder where you run Terraform commands and contains your primary configuration files. It acts like the starting point that calls other modules if used, organizing your infrastructure setup.How It Works
Think of the root module as the main control room of your infrastructure project. It is the folder where you put your Terraform files and run commands like terraform apply. This module can include resources directly or call other smaller modules to build complex setups.
Just like a recipe book has a main recipe that refers to smaller recipes for sauces or sides, the root module is the main recipe that can include other modules. Terraform starts here to understand what infrastructure to create or change.
Example
This example shows a simple root module with a single resource to create an AWS S3 bucket.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 4.0"
}
}
required_version = ">= 1.0"
}
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "example" {
bucket = "my-root-module-bucket-12345"
acl = "private"
}
When to Use
Use the root module whenever you start a new Terraform project. It is where you define your main infrastructure or orchestrate multiple smaller modules. For example, if you build a website, the root module might create the network, servers, and storage by calling separate modules for each.
It helps keep your project organized and makes it easier to manage infrastructure as code by separating concerns into modules but always starting from the root.
Key Points
- The root module is the main folder where Terraform commands run.
- It contains your primary configuration files and can call other modules.
- Terraform always starts processing infrastructure from the root module.
- Organizing code with a root module helps manage complex infrastructure.