Prerequisites
AWS account (free tier works), Terraform installed (brew install terraform), AWS CLI configured (aws configure).
Project Structure
terraform-vpc/
├── main.tf
├── variables.tf
├── outputs.tf
└── terraform.tfvars
variables.tf
hcl
variable "region" { default = "ap-south-1" }
variable "project" { default = "myproject" }
variable "environment" { default = "dev" }
main.tf — Core Resources
hcl
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
}
provider "aws" { region = var.region }
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = { Name = "${var.project}-${var.environment}-vpc" }
}
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index}.0/24"
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = true
}
resource "aws_nat_gateway" "main" {
allocation_id = aws_eip.nat.id
subnet_id = aws_subnet.public[0].id
}
data "aws_availability_zones" "available" { state = "available" }
Apply It
bash
terraform init # Download AWS provider
terraform plan # Preview (23 resources)
terraform apply # Type yes to create
terraform output # See VPC ID and subnet IDs
terraform destroy # Clean up when done
Cost Warning
The NAT Gateway costs ~$0.05/hour. Run terraform destroy when you are done learning to avoid charges.