We may not have the course you’re looking for. If you enquire or give us a call on 01344203999 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Terraform is a tool that allows you to manage your infrastructure as code. However, as your infrastructure grows, you may face challenges such as code duplication, inconsistency, and complexity. That’s where Terraform Modules come in. Terraform Modules are reusable units of configuration that can help you simplify and organise your infrastructure code. In this blog, you will learn what Terraform Modules are, how to use them, and what benefits they offer for your infrastructure as code.
Table of Contents
1) What is a Terraform Module?
2) Types of Terraform Modules
3) How are Terraform Modules Used?
4) Advantages of using Terraform Modules
5) Potential Drawbacks of Terraform Modules
6) Conclusion
What is a Terraform Module?
A Terraform Module is a collection of standard configuration files organised in a dedicated directory. These modules encapsulate groups of resources focused on a single task, reducing the amount of code required for similar infrastructure components.
Terraform Modules are considered a way to extend your current Terraform configuration with reusable code, minimising repetitive development efforts. A Terraform module can be defined as one or multiple “.tf” files contained in their own directory.
Modules can enforce compliance across resources. For example, you can deploy databases with encrypted disks by hard coding the encryption configuration and not exposing it through variables, ensuring disks are always encrypted when the module is used. A typical module structure includes:
├── main.tf ├── outputs.tf ├── README.md └── variables.tf |
Essentially, any Terraform configuration is already a module. Running Terraform in this directory considers those files as a root module, which serves as the base configuration that can be further expanded.
Types of Terraform Modules
1) Root Module
The root module comprises all the resources defined in the “.tf” files of a Terraform configuration, making every Terraform configuration inherently a root module. Even a simple “main.tf” file with just a local variable qualifies as a root module. Remember, any Terraform configuration can be reused as a module in other configurations. Modules can call other modules, and those called within another module are referred to as child modules.
2) Child Module
A child module is included in a configuration by calling it within a module block, thereby incorporating all the resources defined in that module. For example:
module "webservers" { source = "../webservers" } |
You can call the same module multiple times and configure each instance as needed.
3) Local Module
A local module is not published in any registry. Instead, it is sourced directly using the file path to the module's directory. This allows you to reuse and manage configurations locally without needing to upload them to a public or private module registry.
4) Published Module
A published module is one that has been uploaded to a Terraform Registry or a Version Control System (VCS) with an associated tag. When sourcing a published module, the URL from the registry or VCS is used.
How are Terraform Modules Used?
Here, we explain how Terraform Modules are used:
1) State Your Intention to Utilise Terraform Modules
Using a Terraform module involves declaring its usage in your configuration by employing the module block and specifying the required variable values. The module block encapsulates details such as the module's source, version, and meta-arguments. Here, we'll explore how to incorporate Terraform Modules, considering different sources, versions, and meta-arguments.
Module Declaration is given below:
module "terraform_test_module" { source = "spacelift.io/your-org/terraform_test_module" version = "1.0.0" argument_1 = var.test_1 argument_2 = var.test_2 argument_3 = var.test_3 } |
1) Sources: Terraform Modules can reside locally or remotely. For a local module, the source points to the module's directory
module "terraform_test_module" { source = "./terraform-test-module" [...] |
For a VCS-hosted module, like on GitHub, the source references the repository and version:
module "terraform_test_module" { source = [...] |
Modules from registries have a specific URL scheme:
module "terraform_test_module" { source = " version = "1.0.0" [...] |
2) Versions: Versioning safeguards infrastructure from unintended updates. Version constraints are specified using operators:
"=" or no operator: specific version. "!=": any version except the specified one. ">, >=, <, <=": comparisons. "~>": allows only the rightmost part of the version number to increment. |
Example:
module "vpc" { source = "spacelift.io/your-organisation/vpc-module-name/aws" version = "1.0.0" [...] |
Modules from the same source repository are considered the same version.
3) Meta arguments: Meta-arguments are unique parameters that modify how Terraform interprets a declared module. Presently, four such meta-arguments are actively employed that are:
a) Count and for_each: Create multiple instances of the same module or resource.
b) providers: Declare the provider for the module's operation, useful for scenarios with multiple cloud service accounts.
provider "aws" { alias = "frankfurt" region = "eu-central-1" } module "example" { [...] providers = { aws.nested_provider_alias = aws.frankfurt } } |
c) depends_on: Explicitly define dependencies between resources or modules.
Incorporating these elements into your Terraform configuration ensures proper utilisation of modules, offering flexibility, version control, and a clear definition of dependencies. This systematic approach contributes to maintaining a robust and predictable infrastructure.
Gain in-depth knowledge and acquire the skills for easy troubleshooting. Register now for our Microservices Architecture Training!
3) Declare Outputs for Modules
The second step is to declare outputs for the module using the output block. The output block defines the values that the module returns to the caller, such as the ID, the IP address, or the DNS name of the web server. For example, to output the public IP address of the web server module, you can write:
output "web_server_ip" { value = module.web_server.public_ip } |
4) Contain Terraform Modules
The third step is to contain the Terraform Modules using the Terraform block. The Terraform block specifies the Terraform version, the backend, the providers, and any other settings that apply to the module. For example, to specify that the web server module requires Terraform 0.14 or higher and uses the AWS provider, you can write:
terraform { required_version = ">= 0.14" backend "s3" { bucket = "example-terraform-state" key = "web-server-module.tfstate" region = "us-east-1" } } provider "aws" { region = "us-east-1" } |
5) Test Modules
The fourth step is to test the Terraform Modules using the Terraform commands. The Terraform commands allow you to initialise, validate, plan, apply, and destroy the module. For example, to test the web server module, you can run:
# Initialise the module terraform init # Validate the module terraform validate # Plan the module terraform plan # Apply the module terraform apply # Destroy the module terraform destroy |
Learn more about Terraform with our expert led course on Terraform Training! Join now!
Advantages of Using Terraform Modules
Using Terraform Modules has several advantages, such as:
1) Reusability
Terraform Modules allow you to reuse the same configuration across different environments or projects without duplicating code. This reduces duplication, improves consistency, and simplifies maintenance. For example, you can use the same web server module for development, staging, and production environments by changing only the specific variables.
2) Team Collaboration
Terraform Modules enhance team collaboration by enabling the sharing and distribution of common or complex configurations among team members or across organisations. This boosts productivity, quality, and security, as team members can leverage each other's expertise and best practices. For example, publishing a web server module to a Terraform registry allows other teams to incorporate it into their own configurations.
3) Scalability
Terraform Modules enable you to modularise and organise your infrastructure as code, managing it as a hierarchy of components. This enhances performance, reliability, and flexibility, allowing you to scale your infrastructure as needed. For example, a web server module can be a building block for a larger module that includes a load balancer, an auto-scaling group, and a database.
4) Consistent Deployment
Modules enable you to define resource configurations once and deploy them consistently across multiple environments. This minimises errors caused by manual configuration differences, ensuring that development, testing, and production environments closely match.
5) Parameterisation
Terraform Modules support parameterisation, allowing you to customise configurations for different use cases. By providing variables as inputs, modules become adaptable and versatile, catering to various deployment scenarios without duplicating code.
Potential Drawbacks of Terraform Modules
1) Complexity
Modules can introduce significant complexity, particularly when they are nested or highly parameterised. This added complexity can make modules difficult to understand and maintain, posing challenges for larger teams and projects that require a clear and streamlined infrastructure management process.
2) Versioning
Managing module versions can be challenging. When a module is updated, it is crucial to carefully control and synchronise the versions used across different environments. This ensures consistency and avoids unintended changes that could disrupt the stability and reliability of the infrastructure.
3) Flexibility vs. Standardisation
While modules promote standardisation, they can sometimes limit flexibility. Highly abstracted modules may not accommodate all specific use cases, necessitating modifications to meet particular needs. These adjustments can undermine the principle of reusability and require additional effort to maintain standardisation without compromising adaptability.
Conclusion
Terraform Modules offer several benefits for infrastructure as code, such as reusability, team collaboration, and scalability. To use a Terraform Module, you need to declare the module, declare outputs for the module, contain the module, and test the module. Terraform Modules are a powerful and convenient way to manage your infrastructure as code, and you can find many ready-made modules in the Terraform registry or create your own modules for your specific needs.
Become an expert in Cloud Computing today – register now with our Cloud Computing Training! Sign up now!
Frequently Asked Questions
The different source types for calling modules in Terraform include local paths, Terraform Registry, version control systems (e.g., GitHub), and HTTP URLs. These sources enable flexible integration and reuse of module configurations across various environments.
The basic components of a Terraform module include main.tf for resource definitions, variables.tf for input variables, outputs.tf for output values, and optionally README.md for documentation. These files define, configure, and document the module.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Cloud Computing Courses, including the Certified Artificial Intelligence (AI) for Cloud Professionals Course and Microservices Architecture Course. These courses cater to different skill levels, providing comprehensive insights into Cloud Computing Platforms.
Our Cloud Computing Blogs cover a range of topics related to Cloud Technology, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Cloud Computing Skills, The Knowledge Academy's diverse courses and informative blogs have got you covered.
Upcoming Cloud Computing Resources Batches & Dates
Date
Fri 6th Dec 2024
Fri 7th Feb 2025
Fri 4th Apr 2025
Fri 6th Jun 2025
Fri 8th Aug 2025
Fri 3rd Oct 2025
Fri 5th Dec 2025