Write a reusable module for an EC2 instance with inputs, outputs and validation.
AdvancedHands-onWrite-Terraform tasks
Answer
# modules/ec2/variables.tf
variable "name" { type = string }
variable "instance_type" {
type = string
default = "t3.micro"
validation {
condition = can(regex("^t3\\.", var.instance_type))
error_message = "Only t3 family is allowed in this module."
}
}
variable "subnet_id" { type = string }
variable "tags" {
type = map(string)
default = {}
}
# modules/ec2/main.tf
data "aws_ami" "al2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
resource "aws_instance" "this" {
ami = data.aws_ami.al2023.id
instance_type = var.instance_type
subnet_id = var.subnet_id
metadata_options { http_tokens = "required" } # IMDSv2 only
tags = merge(var.tags, { Name = var.name })
}
# modules/ec2/outputs.tf
output "id" { value = aws_instance.this.id }
output "private_ip" { value = aws_instance.this.private_ip }
module "web" {
source = "./modules/ec2"
name = "web-1"
instance_type = "t3.small"
subnet_id = aws_subnet.private["ap-south-1a"].id
}
Key trick → validation blocks reject bad input at plan time with a readable message. Requiring IMDSv2 via http_tokens = "required" is a security default worth mentioning.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.BeginnerWrite Terraform that looks up an existing VPC by tag instead of hardcoding its ID.Intermediate