-
Notifications
You must be signed in to change notification settings - Fork 1
/
ec2.tf
132 lines (108 loc) · 2.75 KB
/
ec2.tf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# 1. Security groups for ALB (Internet -> ALB)
resource "aws_security_group" "alb_sg" {
name = "yt-alb-sg"
description = "Security Group for Application Load Balancer"
vpc_id = aws_vpc.custom_vpc.id
ingress {
from_port = 80
to_port = 80
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 = "yt-alb-sg"
}
}
# 2. Security groups for EC2 Instances (ALB -> EC2)
resource "aws_security_group" "ec2_sg" {
name = "yt-ec2-sg"
description = "Security Group for Web Server Instance"
vpc_id = aws_vpc.custom_vpc.id
ingress {
from_port = 0
to_port = 0
protocol = "-1"
security_groups = [aws_security_group.alb_sg.id]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "yt-ec2-sg"
}
}
# 3. Application Load Balancer
resource "aws_lb" "app_lb" {
name = "yt-app-lb"
load_balancer_type = "application"
internal = false
security_groups = [aws_security_group.alb_sg.id]
subnets = aws_subnet.public_subnet[*].id
depends_on = [aws_internet_gateway.igw_vpc]
}
# Target group for ALB
resource "aws_lb_target_group" "alb_ec2_tg" {
name = "yt-web-server-tg"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.custom_vpc.id
tags = {
Name = "yt-alb_ec2_tg"
}
}
# Listener
resource "aws_lb_listener" "alb_listener" {
load_balancer_arn = aws_lb.app_lb.arn
port = "80"
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.alb_ec2_tg.arn
}
tags = {
Name = "yt-alb-listener"
}
}
# Launch Template for EC2 Instances
resource "aws_launch_template" "ec2_launch_template" {
name = "yt-web-server"
image_id = "ami-0f06718ac552afe18"
instance_type = "t2.micro"
network_interfaces {
associate_public_ip_address = false
security_groups = [aws_security_group.ec2_sg.id]
}
user_data = filebase64("userdata.sh")
tag_specifications {
resource_type = "instance"
tags = {
Name = "yt-ec2-web-server"
}
}
}
# Auto Scaling Groups
resource "aws_autoscaling_group" "ec2_asg" {
max_size = 3
min_size = 2
desired_capacity = 2
name = "yt-web-server-asg"
target_group_arns = [aws_lb_target_group.alb_ec2_tg.arn]
vpc_zone_identifier = aws_subnet.private_subnet[*].id
launch_template {
id = aws_launch_template.ec2_launch_template.id
version = "$Latest"
}
health_check_type = "EC2"
}
output "alb_dns_name" {
value = aws_lb.app_lb.dns_name
}