Introduction
When working with Terraform, it’s common to break infrastructure code into reusable modules. Passing variable data from a root module to a child module is essential for modularity and configuration flexibility. This article explains how to pass variables between a root and child module in Terraform.
Child Module Setup
In the child module, variables must be declared to accept incoming data from the root module. This is done using variable
blocks:
# modules/example/variables.tf
variable "instance_type" {
description = "The type of EC2 instance"
type = string
}
variable "instance_count" {
description = "The number of instances to create"
type = number
}
These variables will be used within the child module’s configuration files.
Using Variables in the Child Module
Within the child module, reference the defined variables wherever they are needed:
# modules/example/main.tf
resource "aws_instance" "example" {
instance_type = var.instance_type
count = var.instance_count
ami = "ami-12345678"
}
Passing Variables from the Root Module
In the root module, use the module
block to call the child module and pass values to the child module’s variables:
# root/main.tf
module "example" {
source = "./modules/example"
instance_type = "t3.micro"
instance_count = 2
}
The source
argument specifies the location of the child module, and the other arguments pass data to the child module’s variables.
Validating the Setup
To ensure the data is passed correctly:
-
Run
terraform init
to initialize the configuration. -
Run
terraform plan
to review the resources that will be created. -
Run
terraform apply
to deploy the infrastructure.
Conclusion
Passing variables between a root and child module in Terraform keeps the code modular, flexible, and easy to manage. By properly defining and using variables, infrastructure can be configured consistently and reused across multiple environments.