Terraform Modules - Day 6

·

2 min read

Terraform modules provide a way to organize and reuse Terraform code by encapsulating a set of resources and configurations into a modular and reusable component. This helps in organizing your infrastructure code and makes it more modular and easier to manage. Once you create a module, you can use it across different parts of your infrastructure or even in different projects. This promotes consistency and reduces duplication of code.

🔸 Modules can take input variables, allowing you to customize their behavior based on the specific requirements of your infrastructure. These variables act as parameters that you can pass when using the module.

🔸 Modules can also define output values, which are variables that are returned when the module is used. This enables the module to communicate specific information or results back to the calling configuration.

Here is a simple example of a Terraform module:

Lets create a module for provisioning a simple EC2 instance.

Step 1: Establish the folder structure as indicated below and position all Terraform configuration files within it.

Configuration file for Provider.

Configuration file for variables.

Configuration file for provisioning an EC2 instance.

Configuration file for outputs: The outputs.tf file below will display the instance ID after creating the resource.

Step 2: Use the module in another Terraform configuration file.

Modules can be sourced from various locations, including local paths, Git repositories, or module registries.

In a parent module, outputs of child modules are available in expression as

module.<MODULE NAME>.<OUTPUT NAME>

Generated output

🔸 Terraform modules can be versioned, enabling you to use a specific version of a module to ensure stability and consistency in your infrastructure.

🔸 Terraform has a module registry where you can publish and share your modules with the community. This facilitates collaboration and allows you to benefit from pre-built, community-contributed modules.

🔹References

1. Reference to publishing modules in Terraform Registry:

https://developer.hashicorp.com/terraform/registry/modules/publish

2. Reference to Terraform Registry modules

https://registry.terraform.io/browse/modules