Working with Modules
In Terraform, modules are reusable pieces of infrastructure code that can be used to provision and manage resources. Think of modules as building blocks for organizing and reusing Terraform code.
Modules help to improve the maintainability, scalability, and reusability of your Terraform configurations. They allow you to define and encapsulate a specific set of resources with their own configurations, inputs, and outputs.
When working with modules, you can:
- Create reusable modules: Create modules that can be shared and reused across different projects or environments. For example, you can create a module that provisions an AWS Virtual Private Cloud (VPC) and reuse it in multiple projects.
- Pass variables to modules: Modules can accept input variables, allowing you to customize the behavior of the module. For example, you can pass the desired VPC CIDR block as an input variable to the VPC module.
- Use outputs from modules: Modules can have output values that can be used by other parts of your Terraform configuration. For example, you can get the VPC ID as an output value from the VPC module and use it in other resources or modules.
To work with modules in Terraform, you define a module
block in your configuration file. This module
block specifies the source of the module, the version (optional), and any input variables that should be passed to the module.
Here's an example of how to use a module to provision an AWS VPC:
1module "vpc" {
2 source = "terraform-aws-modules/vpc/aws"
3 version = "2.81.0"
4
5 name = "my-vpc"
6 cidr = "10.0.0.0/16"
7
8 tags = {
9 Name = "My VPC"
10 }
11}
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Replace with your Terraform module code here
// For example, define a module that provisions an AWS VPC
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "2.81.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
tags = {
Name = "My VPC"
}
}
// Replace with your module output code here
// For example, get an output from the VPC module
output "vpc_id" {
value = module.vpc.vpc_id
}
}
}