Terraform, the popular Infrastructure as Code (IaC) tool, has made managing cloud infrastructure much easier and efficient. One of the key aspects of Terraform is its modular approach, allowing users to create reusable modules for different components of their infrastructure. In this blog post, we will walk you through creating a Terraform module from scratch and provide a comprehensive understanding of the process.

Prerequisites:

  • A basic understanding of Terraform and Infrastructure as Code
  • Terraform installed on your local machine
  • Access to a cloud provider account (e.g., AWS, Azure, or GCP)

Step 1: Plan Your Module

Before diving into the code, it's essential to plan your module. Identify the resources you want to create and any dependencies they might have. For this tutorial, we will create a Terraform module to deploy an AWS EC2 instance along with a security group and an Elastic IP.

Step 2: Create a New Directory

Create a new directory for your module. This will keep your module's code organized and separate from other modules or configurations. For this example, create a directory called aws_ec2_instance.

$ mkdir aws_ec2_instance

Step 3: Define the Main Configuration File

Inside the aws_ec2_instance directory, create a main.tf file. This is where we will define the main resources for our module.

main.tf:

resource "aws_instance" "this" {
ami = var.ami
instance_type = var.instance_type
key_name = var.key_name
subnet_id = var.subnet_id

vpc_security_group_ids = [aws_security_group.this.id]

tags = {
Name = var.instance_name
}
}

resource "aws_security_group" "this" {
name = "${var.instance_name}-sg"
description = "Security Group for the EC2 instance"
vpc_id = var.vpc_id
}

resource "aws_eip" "this" {
instance = aws_instance.this.id
vpc = true
}

Step 4: Define Module Variables

In the aws_ec2_instance directory, create a variables.tf file. This will contain the input variables required for the module. These variables allow users to customize the module's configuration.

variables.tf:

variable "ami" {
description = "The Amazon Machine Image (AMI) ID for the EC2 instance."
type = string
}

variable "instance_type" {
description = "The type of the EC2 instance."
type = string
}

variable "key_name" {
description = "The name of the key pair to use for the EC2 instance."
type = string
}

variable "subnet_id" {
description = "The ID of the VPC subnet in which the EC2 instance will be launched."
type = string
}

variable "vpc_id" {
description = "The ID of the VPC in which the security group will be created."
type = string
}

variable "instance_name" {
description = "The name of the EC2 instance."
type = string
}

Step 5: Define Module Outputs

Create an outputs.tf file in the aws_ec2_instance directory to define the output values that users can access after the module has been executed.

outputs.tf:

output "instance_id" {
value = aws_instance.this.id
description = "The ID of the EC2 instance."
}

output