Understanding the Root Module
Consider a configuration directory named “aws-instance” located under your Terraform projects directory. This folder contains the configuration files needed to deploy a simple EC2 instance on AWS. Since Terraform commands are executed inside this folder, “aws-instance” serves as the root module for that configuration. For example, listing the contents of the “aws-instance” directory:main.tf file might include the following configuration:
variables.tf file could define variables like this:
Reusing Modules with Child Modules
Terraform modules can also reference other modules, enabling you to package and reuse resource configurations efficiently. Suppose you wish to create a new development web server instance using the existing “aws-instance” module. Instead of duplicating the configuration, you can simply call the module from a new directory called “development.” First, create the new directory:source parameter that provides the path to the module. You can also specify an absolute path:
Using absolute paths can be effective in some scenarios, but it is generally recommended to use relative paths for portability.
Leveraging the Terraform Registry
One of the key benefits of using modules is code reusability. In addition to local modules, you can also utilize modules hosted on the Terraform Registry, which is a robust repository for both provider plugins and community or official modules. For example, instead of writing a security group configuration from scratch, you might search for a suitable module in the Registry. Below is an example search result:
Example: Using an AWS Security Group Module
To use a module for creating a security group in your configuration, include a module block with the appropriate source and version specifications. For instance:-
Initialize Terraform:
Download necessary provider plugins and modules by running: -
Plan and Apply:
Validate the configuration withterraform planand create the resources usingterraform apply.
Remember that running
terraform init, terraform plan, and terraform apply in the directory where your root module is located is crucial for successful deployment.Benefits of Using Modules
Modules in Terraform offer numerous advantages:| Benefit | Description |
|---|---|
| Reusability | Encapsulate resources in self-contained units that can be reused across multiple projects. |
| Simplified Configuration | Reduce configuration complexity by abstracting detailed setups into modules. |
| Improved Readability | Maintain shorter and more understandable root modules. |
| Reduced Risk of Human Error | Use tested and validated modules to minimize errors. |
| Configuration Locking | Restrict specific variables in the root module to enforce standard parameters. |