Lab Terraform Day3 1
Lab Terraform Day3 1
Project Overview
We'll deploy:
A VPC.
Two subnets (public and private).
An Internet Gateway for the public subnet.
An EC2 instance in the public subnet.
Directory Structure
terraform-aws-project/
├── main.tf # Core resources (VPC, subnets, EC2, etc.)
├── variables.tf # Input variables for configuration
├── outputs.tf # Outputs for key resource values
├── provider.tf # AWS provider configuration
├── terraform.tfvars # Variable values (secrets, environment-specific configs)
├── backend.tf # Remote backend configuration (optional)
└── modules/ # Reusable modules
└── ec2/ # Example module for EC2 instances
├── main.tf
├── variables.tf
├── outputs.tf
provider "aws" {
region = "ap-southeast-2"
}
variable "vpc_cidr" {
description = "CIDR block for the VPC"
default = "10.0.0.0/16"
}
variable "public_subnet_cidr" {
description = "CIDR block for the public subnet"
default = "10.0.1.0/24"
}
variable "private_subnet_cidr" {
description = "CIDR block for the private subnet"
default = "10.0.2.0/24"
}
variable "instance_type" {
description = "EC2 instance type"
default = "t2.micro"
}
# VPC
resource "aws_vpc" "main_vpc" {
cidr_block = var.vpc_cidr
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "TerraformVPC"
}
}
# Public Subnet
resource "aws_subnet" "public_subnet" {
vpc_id = aws_vpc.main_vpc.id
cidr_block = var.public_subnet_cidr
map_public_ip_on_launch = true
tags = {
Name = "PublicSubnet"
}
}
# Private Subnet
resource "aws_subnet" "private_subnet" {
vpc_id = aws_vpc.main_vpc.id
cidr_block = var.private_subnet_cidr
tags = {
Name = "PrivateSubnet"
}
}
# Internet Gateway
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main_vpc.id
tags = {
Name = "InternetGateway"
}
}
ingress {
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"]
}
tags = {
Name = "AllowSSH"
}
}
# EC2 Instance
module "ec2_instance" {
source = "./modules/ec2"
instance_type = var.instance_type
public_subnet = aws_subnet.public_subnet.id
security_group = aws_security_group.allow_ssh.id
}
4. Outputs (outputs.tf)
output "vpc_id" {
value = aws_vpc.main_vpc.id
}
output "public_subnet_id" {
value = aws_subnet.public_subnet.id
}
output "ec2_public_ip" {
value = module.ec2_instance.public_ip
}
5. Module for EC2 (modules/ec2/main.tf)
Reason: Reusable EC2 module.
tags = {
Name = "TerraformInstance"
}
}
output "public_ip" {
value = aws_instance.instance.public_ip
}
variable "instance_type" {
description = "Type of instance to launch"
}
variable "public_subnet" {
description = "ID of the public subnet"
}
variable "security_group" {
description = "ID of the security group"
}
output "public_ip" {
value = aws_instance.instance.public_ip
}