Modules are containers for multiple resources that are used together. A module consists of a collection of .tf and/or .tf.json files kept together in a directory
A module can call other modules, which lets you include the child module's resources in the configuration concisely.
Modules can also be called multiple times, either within the same configuration or in separate configurations, allowing resource configurations to be packaged and re-used.
Below is the format on how to use modules:
# Creating a AWS EC2 Instance
resource "aws_instance" "server-instance" {
# Define number of instance
instance_count = var.number_of_instances
# Instance Configuration
ami = var.ami
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = var.security_group
# Instance Tagsid
tags = {
Name = "${var.instance_name}"
}
}
# Server Module Variables
variable "number_of_instances" {
description = "Number of Instances to Create"
type = number
default = 1
}
variable "instance_name" {
description = "Instance Name"
}
variable "ami" {
description = "AMI ID"
default = "ami-xxxx"
}
variable "instance_type" {
description = "Instance Type"
}
variable "subnet_id" {
description = "Subnet ID"
}
variable "security_group" {
description = "Security Group"
type = list(any)
}
# Server Module Output
output "server_id" {
description = "Server ID"
value = aws_instance.server-instance.id
}
Different Modules in Terraform:
In Terraform, modules are like building blocks for creating and organizing your infrastructure as code (IAC). Think of them as self-contained units that group related resources and their configurations. Modules are a way to abstract, reuse, and organize your infrastructure code. You can create modules for various purposes, such as defining a web server configuration, a database setup, or a VPC (Virtual Private Cloud) layout. Each module encapsulates a specific set of resources and configurations, making your code more modular, maintainable, and reusable.
The difference between the root module and the child module:
Modules vs. Namespaces:
No, Modules and Namespaces are not the same.
Thank you so much for reading
Follow me on LinkedIn to see interesting posts like this : )