.tf extension in the configuration directory, regardless of the file organization.
Below is an example of how you might structure your Terraform files across multiple files:
- Increasing complexity and code duplication within the configuration directory.
- The risk of unintended changes affecting resources in different parts of the configuration.
Using modules in Terraform allows you to manage complexity, reduce code duplication, and enhance reusability across projects and environments.
What Is a Terraform Module?
A Terraform module is any directory that contains a set of.tf files. Essentially, every Terraform configuration directory is a module. For example, consider a configuration directory named aws-instance located under /root/terraform-projects. This directory contains the Terraform files required to create a simple EC2 instance in AWS. Since it has valid Terraform configuration files, it qualifies as a module.
Here is the directory listing for the aws-instance module:
main.tf might look like this:
variables.tf defines the variables:
aws-instance directory, it is considered the root module.
Reusing Modules for Different Environments
Now, imagine you want to reuse theaws-instance module to create a new development web server instance without duplicating code. Follow these steps to create a development environment:
-
Create a new directory named
developmentunder theterraform-projectsdirectory: -
Inside the
developmentdirectory, create a configuration file (for example,main.tf) that references theaws-instancemodule:
development directory serves as the root module (because you run Terraform commands from here), while the aws-instance directory is referenced as a child module.
Let’s review the module block again:
module keyword is followed by a logical name, in this case, dev-webserver. Within the block, the required argument is source, which specifies the relative or absolute path to the child module containing the Terraform configuration for the EC2 instance. Here, we use a relative path "../aws-instance", pointing to the corresponding directory next to our development directory.
This modular approach effectively addresses earlier challenges by reducing code duplication, simplifying updates, and boosting reusability. It encapsulates specific infrastructure logic in a module that can be reused across different environments or projects.
Modules not only help in organizing your Terraform configurations but also promote best practices by isolating infrastructure components. This makes your configurations easier to manage and share.