-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.tf
440 lines (359 loc) · 11.5 KB
/
main.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#-----------------------------
# VPC MODULE
#-----------------------------
locals {
azs = slice(data.aws_availability_zones.available.names, 0, var.nr_az)
}
# trunk-ignore(checkov/CKV_TF_1)
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~>5.19.0"
name = var.vpc_name
cidr = var.vpc_cidr
azs = local.azs
private_subnets = [for k, v in local.azs : cidrsubnet(var.vpc_cidr, 8, k)]
public_subnets = [for k, v in local.azs : cidrsubnet(var.vpc_cidr, 8, k + 8)]
database_subnets = [for k, v in local.azs : cidrsubnet(var.vpc_cidr, 8, k + 16)]
create_database_subnet_group = true
enable_dns_hostnames = true
enable_dns_support = true
enable_nat_gateway = true
single_nat_gateway = true
}
#-----------------------------
# SECURITY GROUPS
#-----------------------------
# Due to circular reference, we need to create the security groups in two steps
# 1. Create the security groups
module "security_group" {
source = "./modules/security-group"
security_groups = {
"web-sg" = {
vpc_id = module.vpc.vpc_id
description = "Security group for web tier"
ingress = {}
egress = {}
},
"app-sg" = {
vpc_id = module.vpc.vpc_id
description = "Security group for application tier"
ingress = {}
egress = {}
},
"db-sg" = {
vpc_id = module.vpc.vpc_id
description = "Security group for database tier"
ingress = {}
egress = {}
},
}
}
# 2. Create the security group rules
# This is where we reference the security groups created in the previous step - map key is the security group name
module "security_group_rules" {
source = "./modules/security-group"
security_groups = {
# Web Tier - allow communication in and out from the internet on ports 80 and 443
"web-sg" = {
ingress = {
"Allow HTTP traffic" = { from_port = 80, to_port = 80, protocol = "tcp", source = ["0.0.0.0/0"], self = false }
"Allow HTTPS traffic" = { from_port = 443, to_port = 443, protocol = "tcp", source = ["0.0.0.0/0"], self = false }
}
egress = {
"All outbound traffic" = { from_port = 0, to_port = 65535, protocol = "-1", source = ["0.0.0.0/0"], self = false }
}
},
# Application Tier - allow communication with the web tier on port 8080
"app-sg" = {
ingress = {
"Allow web-tier" = { from_port = 8080, to_port = 8080, protocol = "tcp", source = [module.security_group.security_groups["web-sg"].id], self = false }
}
egress = {
"All outbound traffic" = { from_port = 0, to_port = 65535, protocol = "-1", source = ["0.0.0.0/0"], self = false }
}
},
# Database Tier - allow communication with the app tier on port 3306
"db-sg" = {
ingress = {
"Allow app-tier" = { from_port = 3306, to_port = 3306, protocol = "tcp", source = [module.security_group.security_groups["app-sg"].id], self = false }
}
egress = {
"All outbound traffic" = { from_port = 0, to_port = 65535, protocol = "-1", source = ["0.0.0.0/0"], self = false }
}
},
}
}
#-----------------------------
# WEB TIER - APPLICATION LOAD BALANCER & AUTO SCALING GROUP
#-----------------------------
# ALB for Web Tier
# trunk-ignore(checkov/CKV2_AWS_28)
# trunk-ignore(checkov/CKV_AWS_131)
resource "aws_lb" "web" {
name = "web-alb"
internal = false
load_balancer_type = "application"
security_groups = [module.security_group.security_groups["web-sg"].id]
subnets = module.vpc.public_subnets
enable_deletion_protection = true
access_logs {
bucket = data.aws_s3_bucket.lb_logs.id
prefix = "web-lb"
enabled = true
}
}
# Launch Template for Web Tier
resource "aws_launch_template" "web" {
name_prefix = "web-template"
image_id = data.aws_ami.latest_amazon_linux.id # Amazon Linux 2 AMI ID
instance_type = var.web_instance_type
vpc_security_group_ids = [module.security_group.security_groups["web-sg"].id]
user_data = base64encode(<<-EOF
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
EOF
)
metadata_options {
http_tokens = "required"
http_put_response_hop_limit = 1
instance_metadata_tags = "enabled"
}
}
# Auto Scaling Group for Web Tier
resource "aws_autoscaling_group" "web" {
desired_capacity = 2
max_size = 6
min_size = 2
target_group_arns = [aws_lb_target_group.web.arn]
vpc_zone_identifier = module.vpc.public_subnets
launch_template {
id = aws_launch_template.web.id
version = "$Latest"
}
tag {
key = "Name"
value = "web-asg"
propagate_at_launch = true
}
lifecycle {
create_before_destroy = true
}
}
# Add autoscaling policy to scale based on CPU utilization
resource "aws_autoscaling_policy" "web_cpu_policy" {
name = "web-cpu-policy"
autoscaling_group_name = aws_autoscaling_group.web.name
policy_type = "TargetTrackingScaling"
target_tracking_configuration {
predefined_metric_specification {
predefined_metric_type = "ASGAverageCPUUtilization"
}
target_value = 70.0
}
}
# Target Group for Web Tier
resource "aws_lb_target_group" "web" {
name = "web-tg"
port = 80
protocol = "HTTP"
vpc_id = module.vpc.vpc_id
health_check {
path = "/"
healthy_threshold = 2
unhealthy_threshold = 5
timeout = 5
interval = 30
}
}
# HTTP Listener for Web ALB
resource "aws_lb_listener" "web-http" {
load_balancer_arn = aws_lb.web.arn
port = "80"
protocol = "HTTP"
default_action {
type = "redirect"
redirect {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
}
# HTTPS Listener for Web ALB
resource "aws_lb_listener" "web-https" {
load_balancer_arn = aws_lb.web.arn
port = "443"
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-TLS-1-2-2017-01"
certificate_arn = data.aws_acm_certificate.issued.arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.web.arn
}
}
# CloudWatch Alarm for Web Tier
resource "aws_cloudwatch_metric_alarm" "web_cpu" {
alarm_name = "web-cpu-alarm"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = "300"
statistic = "Average"
threshold = "80"
actions_enabled = "true"
alarm_description = "CPU usage on the web tier instances higher than 80%"
alarm_actions = [data.aws_sns_topic.alert.arn]
ok_actions = [data.aws_sns_topic.alert.arn]
dimensions = {
AutoScalingGroupName = aws_autoscaling_group.web.name
}
}
#-----------------------------
# APPLICATION TIER - LAUNCH CONFIGURATION & AUTO SCALING GROUP
#-----------------------------
# Launch Template for Application Tier
resource "aws_launch_template" "app" {
name_prefix = "app-template"
image_id = data.aws_ami.latest_amazon_linux.id # Amazon Linux 2 AMI ID
instance_type = var.app_instance_type
vpc_security_group_ids = [module.security_group.security_groups["app-sg"].id]
user_data = base64encode(<<-EOF
#!/bin/bash
yum update -y
yum install -y demo-app
EOF
)
metadata_options {
http_tokens = "required"
http_put_response_hop_limit = 1
instance_metadata_tags = "enabled"
}
}
# Application Load Balancer for App Tier
# trunk-ignore(checkov/CKV2_AWS_20)
# trunk-ignore(checkov/CKV_AWS_131)
resource "aws_lb" "app" {
name = "app-internal-alb"
internal = true
load_balancer_type = "application"
security_groups = [module.security_group.security_groups["app-sg"].id]
subnets = module.vpc.private_subnets
enable_deletion_protection = true
access_logs {
bucket = data.aws_s3_bucket.lb_logs.id
prefix = "app-lb"
enabled = true
}
}
# Target Group for App Tier
# trunk-ignore(checkov/CKV_AWS_378)
resource "aws_lb_target_group" "app" {
name = "app-tg"
port = 8080
protocol = "HTTP"
vpc_id = module.vpc.vpc_id
health_check {
path = "/api/health"
healthy_threshold = 2
unhealthy_threshold = 10
timeout = 5
interval = 30
}
stickiness {
type = "lb_cookie"
cookie_duration = 86400
enabled = true
}
}
# Auto Scaling Group for App Tier
resource "aws_autoscaling_group" "app" {
desired_capacity = 2
max_size = 4
min_size = 2
target_group_arns = [aws_lb_target_group.app.arn]
vpc_zone_identifier = module.vpc.private_subnets
launch_template {
id = aws_launch_template.app.id
version = "$Latest"
}
lifecycle {
create_before_destroy = true
}
tag {
key = "Name"
value = "app-asg"
propagate_at_launch = true
}
}
# Add autoscaling policy to scale based on CPU utilization
resource "aws_autoscaling_policy" "app_cpu_policy" {
name = "app-cpu-policy"
autoscaling_group_name = aws_autoscaling_group.app.name
policy_type = "TargetTrackingScaling"
target_tracking_configuration {
predefined_metric_specification {
predefined_metric_type = "ASGAverageCPUUtilization"
}
target_value = 60.0
}
}
# Listener for App ALB
# trunk-ignore(checkov/CKV_AWS_2)
# trunk-ignore(checkov/CKV_AWS_103)
resource "aws_lb_listener" "app" {
load_balancer_arn = aws_lb.app.arn
port = "8080"
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.app.arn
}
}
#-----------------------------
# DATABASE
#-----------------------------
# Generate Password
resource "random_password" "main" {
length = 20
special = true # Default: !@#$%&*()-_=+[]{}<>:?
override_special = "!$&-_=+<>"
}
# Save credentials in Secrets Manager
# trunk-ignore(checkov/CKV2_AWS_57)
resource "aws_secretsmanager_secret" "rds_cred" {
name = "rds/mysql-${var.db_name}-credentials"
kms_key_id = data.aws_kms_key.secret-manager.arn
}
resource "aws_secretsmanager_secret_version" "rds_cred" {
secret_id = aws_secretsmanager_secret.rds_cred.id
secret_string = jsonencode({
username = var.db_username
password = random_password.main.result
endpoint = module.rds.db_instance_address
port = module.rds.db_instance_port
db_name = var.db_name
})
}
# Create one MySQL RDS instance
# trunk-ignore(checkov/CKV_TF_1)
module "rds" {
source = "terraform-aws-modules/rds/aws"
version = "~> 5.0"
identifier = var.db_name
family = var.rds_engine["family"]
engine = var.rds_engine["engine"]
engine_version = var.rds_engine["engine_version"]
major_engine_version = var.rds_engine["major_engine_version"]
instance_class = "db.t3.micro"
allocated_storage = 20
username = var.db_username
password = random_password.main.result
vpc_security_group_ids = [module.security_group.security_groups["db-sg"].id]
subnet_ids = module.vpc.database_subnets
publicly_accessible = false
db_subnet_group_name = module.vpc.database_subnet_group_name
}