Modules
Terraform modules are containers for multiple resources that are used together. They promote reusability and maintainability in Terraform configurations. Understanding how to create and use modules is a key skill in Terraform.
What Are Terraform Modules?
-
Purpose of Modules:
- Modules allow you to package and encapsulate a group of resources and configurations for reuse.
- They help in organizing complex Terraform configurations into manageable chunks.
-
Types of Modules:
- Root Module: The main configuration directory is considered a root module.
- Child Modules: Reusable modules sourced from other directories or remote sources.
Creating a Module
-
Module Structure:
- A typical module includes main configuration files (
main.tf), variables (variables.tf), outputs (outputs.tf), and optionally, documentation (README.md).
- A typical module includes main configuration files (
-
Defining Resources:
- Inside the module, define the resources that it manages. For example, a module for an AWS EC2 instance might include resource definitions for the instance, security group, and key pair.
-
Using Variables and Outputs:
- Use input variables to customize modules.
- Define output values to return information about the resources in the module.
Using a Module
-
Source a Module:
- In your root module, reference the child module using the
sourceattribute. - The
sourcecan be a local path or a remote source, like a Terraform Registry URL or a Git repository.
- In your root module, reference the child module using the
-
Passing Inputs:
- Provide values for the module’s input variables.
-
Example Usage:
module "ec2_instance" {
source = "./modules/ec2"
instance_type = "t2.micro"
ami = "ami-123456"
}
Best Practices
- Documentation: Document your modules, explaining their purpose, inputs, and outputs.
- Versioning: Use versioned sources for modules, especially when using remote sources, to ensure consistent and predictable usage.
- Testing: Regularly test your modules to ensure they work as expected.