Skip to main content

VPC avec Terraform & AWS

S3-terraform.jpg

Listes des .tf

main.tf

# create a VPC
resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
  tags = { Name = var.vpc_tag }  # utilise vpc_tag
}

# subnet public
resource "aws_subnet" "pub" {
  count      = length(var.vpc_subnet_pub)
  vpc_id     = aws_vpc.main.id
  cidr_block = var.vpc_subnet_pub[count.index] 
  tags = {
    Name = "subnet_${var.vpc_subnet_pub[count.index]}"
  }
}

# subnet private
resource "aws_subnet" "priv" {
  count      = length(var.vpc_subnet_priv)
  vpc_id     = aws_vpc.main.id
  cidr_block = var.vpc_subnet_priv[count.index] 
  tags = {
    Name = "subnet_${var.vpc_subnet_priv[count.index]}"
  }
}

# IGW / internet gateway
resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.main.id
  tags   = { Name = "IGW" }
}

# EIP pour NAT
resource "aws_eip" "nat_eip" {
  domain = "vpc"
}

#NAT GW dans SUB1 publique
resource "aws_nat_gateway" "nat" {
  allocation_id = aws_eip.nat_eip.id
  subnet_id     = aws_subnet.pub[0].id  
  tags          = { Name = "NAT-GW" }
}

# table routage publique (0.0.0/0 -> IGW)
resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.igw.id
  }
  tags = { Name = "RT-public" }
}

# association RT publique aux SUB1/SUB2
resource "aws_route_table_association" "pub" {
  count          = length(var.vpc_subnet_pub)
  subnet_id      = aws_subnet.pub[count.index].id 
  route_table_id = aws_route_table.public.id
}

# table routage private (0.0.0/0 -> IGW)
resource "aws_route_table" "private" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.nat.id
  }
  tags = { Name = "RT-private" }
}

# association RT privée à SUB3/SUB4
resource "aws_route_table_association" "priv" {
  count          = length(var.vpc_subnet_priv)
  subnet_id      = aws_subnet.priv[count.index].id  # public → priv
  route_table_id = aws_route_table.private.id       # public → private
}

variables.tf

variable "vpc_cidr" {
  description = "Plage CIDR du VPC"
  type        = string
  default     = "10.0.0.0/16"
}

variable "vpc_subnet_pub" {
  description = "CIDRs des subnets publics"
  type        = list(string)                        # ← string → list(string)
  default     = ["10.0.1.0/24", "10.0.11.0/24"]    # ← virgule → liste
}

variable "vpc_subnet_priv" {
  description = "CIDRs des subnets privés"
  type        = list(string)                        # ← string → list(string)
  default     = ["10.0.2.0/24", "10.0.21.0/24"]    # ← virgule → liste
}

variable "vpc_tag" {
  description = "Tag name du VPC"
  type        = string
  default     = "cesi"
}