1+ terraform {
2+ required_providers {
3+ aws = {
4+ source = " hashicorp/aws"
5+ version = " ~> 5.0"
6+ }
7+ }
8+ }
9+
10+ provider "aws" {
11+ region = var. aws_region
12+ }
13+
14+ # Get available AZs
15+ data "aws_availability_zones" "available" {}
16+
17+ # VPC - Your isolated network
18+ resource "aws_vpc" "main" {
19+ cidr_block = " 10.0.0.0/16"
20+ enable_dns_hostnames = true
21+ enable_dns_support = true
22+
23+ tags = {
24+ Name = " main-vpc"
25+ }
26+ }
27+
28+ # Internet Gateway for public access
29+ resource "aws_internet_gateway" "main" {
30+ vpc_id = aws_vpc. main . id
31+
32+ tags = {
33+ Name = " main-igw"
34+ }
35+ }
36+
37+ # Public subnets for load balancer
38+ resource "aws_subnet" "public" {
39+ count = 2
40+ vpc_id = aws_vpc. main . id
41+ cidr_block = " 10.0.${ count . index + 1 } .0/24"
42+ availability_zone = data. aws_availability_zones . available . names [count . index ]
43+
44+ map_public_ip_on_launch = true
45+
46+ tags = {
47+ Name = " public-subnet-${ count . index + 1 } "
48+ }
49+ }
50+
51+ # Private subnets for application servers
52+ resource "aws_subnet" "private" {
53+ count = 2
54+ vpc_id = aws_vpc. main . id
55+ cidr_block = " 10.0.${ count . index + 10 } .0/24"
56+ availability_zone = data. aws_availability_zones . available . names [count . index ]
57+
58+ tags = {
59+ Name = " private-subnet-${ count . index + 1 } "
60+ }
61+ }
62+
63+ # Security group for ALB
64+ resource "aws_security_group" "alb" {
65+ name_prefix = " alb-sg"
66+ vpc_id = aws_vpc. main . id
67+
68+ ingress {
69+ from_port = 80
70+ to_port = 80
71+ protocol = " tcp"
72+ cidr_blocks = [" 0.0.0.0/0" ]
73+ }
74+
75+ egress {
76+ from_port = 0
77+ to_port = 0
78+ protocol = " -1"
79+ cidr_blocks = [" 0.0.0.0/0" ]
80+ }
81+ }
82+
83+ # Application Load Balancer
84+ resource "aws_lb" "main" {
85+ name = " main-alb"
86+ internal = false
87+ load_balancer_type = " application"
88+ security_groups = [aws_security_group . alb . id ]
89+ subnets = aws_subnet. public [* ]. id
90+
91+ enable_deletion_protection = false
92+
93+ tags = {
94+ Name = " main-alb"
95+ }
96+ }
0 commit comments