Terraform Project: Simple EC2 + Security Group
Source: Dev.to
Project Structure
terraform-project/
│── main.tf
│── variables.tf
│── outputs.tf
│── providers.tf
│── terraform.tfvars
│── modules/
│ └── ec2/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
└── README.md
providers.tf
Defines AWS provider + region.
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
variables.tf
All input variables.
variable "aws_region" {
description = "AWS region"
type = string
default = "us-east-2"
}
variable "instance_type" {
description = "EC2 instance size"
type = string
default = "t2.micro"
}
variable "project_name" {
description = "Tag for resources"
type = string
default = "tf-demo"
}
main.tf
Calls module and passes variables.
module "ec2_demo" {
source = "./modules/ec2"
instance_type = var.instance_type
project_name = var.project_name
}
outputs.tf
output "ec2_public_ip" {
description = "Public IP of EC2"
value = module.ec2_demo.public_ip
}
output "ec2_id" {
description = "EC2 Instance ID"
value = module.ec2_demo.instance_id
}
terraform.tfvars (optional inputs)
aws_region = "us-east-2"
instance_type = "t2.micro"
project_name = "students-demo"
Module: modules/ec2/main.tf
Creates a security group and an EC2 instance with tags.
resource "aws_security_group" "demo_sg" {
name = "${var.project_name}-sg"
description = "Allow SSH"
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "demo" {
ami = "ami-0c02fb55956c7d316" # Amazon Linux 2 us-east-2
instance_type = var.instance_type
security_groups = [aws_security_group.demo_sg.name]
tags = {
Name = "${var.project_name}-ec2"
}
}
Module: modules/ec2/variables.tf
variable "instance_type" {
type = string
}
variable "project_name" {
type = string
}
Module: modules/ec2/outputs.tf
output "public_ip" {
value = aws_instance.demo.public_ip
}
output "instance_id" {
value = aws_instance.demo.id
}
How to Run (Teaching Steps)
-
Initialize Terraform
terraform init -
Validate configuration
terraform validate -
Review the execution plan
terraform plan -
Apply the configuration
terraform apply -auto-approve -
View output values
terraform output -
Destroy the infrastructure when finished
terraform destroy -auto-approve
What Students Learn From This Project
| Component | What it Teaches |
|---|---|
providers.tf | Provider setup, version constraints |
variables.tf | Variables, types, defaults |
terraform.tfvars | Overriding default values |
main.tf | Calling modules |
modules/ | Real‑world production design |
| EC2 + SG | Simple infrastructure provisioning |
outputs.tf | Exporting values |
Terraform workflow (init, plan, apply, destroy) | Full lifecycle management |