Skip to main content

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?

  1. 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.
  2. 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

  1. Module Structure:

    • A typical module includes main configuration files (main.tf), variables (variables.tf), outputs (outputs.tf), and optionally, documentation (README.md).
  2. 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.
  3. 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

  1. Source a Module:

    • In your root module, reference the child module using the source attribute.
    • The source can be a local path or a remote source, like a Terraform Registry URL or a Git repository.
  2. Passing Inputs:

    • Provide values for the module’s input variables.
  3. 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.