Terraform Use Output from Another Module: Effective Guide
Core Idea
A Terraform module is a reusable bundle of
.tffiles in its own directory: every configuration is already a root module, and calling one from another makes it a child module.
- Root modules versus child modules, and why even a single
_locals_block counts as a root module.- Local modules versus published ones (registry or VCS with a tag), called with a
moduleblock.- Modules versus resources: a resource is one piece of infrastructure, a module is a reusable group of them.
What is Terraform Module
Abstract
A Terraform module is a collection of standard configuration files in a dedicated directory. Terraform modules encapsulate groups of resources dedicated to one task, reducing the amount of code you have to develop for similar infrastructure components.
A typical module can look like this:
.
├── main.tf
├── outputs.tf
├── README.md
└── variables.tfpractically any Terraform configuration is already a module in itself.
If you run Terraform in this directory, those configuration files would be considered a root module. It means that this configuration is the base of your operation, a core that you can expand further.
Difference between resources and modules in Terraform?
A resource in Terraform describes a piece of infrastructure that is going to be created (e.g., a VPC, a subnet, an ec2 instance, etc), whereas a module is a collection of resources that are used together to achieve a reusable use case.
Types of Modules
Root Module
The root module consists of all the resources defined in the .tf files in a Terraform configuration, meaning that all Terraform configurations have their own root module.
Even if you are simply creating a main.tf that has just a locals block inside of it with a local variable, that is still considered a root module.
This can be confusing, but keep in mind that every Terraform configuration can become a reusable module for other configurations. Every module can call other modules, and all of the modules called inside another module are considered child modules.
Child Module
Calling a child module means to include all the resources defined in that module in the current configuration. This is done by using a module block inside your Terraform configuration:
module "webservers" {
source = "../webservers"
}You can call the same module as many times as you want and configure it to your liking.
Local module
A local module is a module that wasn’t published in any registry and when it is sourced, it is using the path to that particular module.
Published module
A published module refers to a module that has been pushed to a Terraform Registry, or even simply on a VCS and has a tag associated with it. When a published module is sourced, the URL of that module is used either from the registry or from the VCS itself.