Interview Prep/Real-World Interview/Write-Terraform tasks

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.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks