-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.tf
1381 lines (1250 loc) · 54.1 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/////////////////////////////////////////////////[ AWS BUDGET NOTIFICATION ]//////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create alert when your budget thresholds are forecasted to exceed
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_budgets_budget" "all" {
name = "${var.app["brand"]}-budget-monthly-forecasted"
budget_type = "COST"
limit_amount = "100"
limit_unit = "USD"
time_unit = "MONTHLY"
notification {
comparison_operator = "GREATER_THAN"
threshold = 100
threshold_type = "PERCENTAGE"
notification_type = "FORECASTED"
subscriber_email_addresses = [var.app["admin_email"]]
}
}
///////////////////////////////////////////////////[ RANDOM STRING GENERATOR ]////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Generate random uuid string that is intended to be used as unique identifier
# # ---------------------------------------------------------------------------------------------------------------------#
resource "random_uuid" "this" {
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Generate random passwords
# # ---------------------------------------------------------------------------------------------------------------------#
resource "random_password" "this" {
for_each = toset(["rds"])
length = 16
lower = true
upper = true
number = true
special = true
override_special = "%*?"
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Generate random string
# # ---------------------------------------------------------------------------------------------------------------------#
resource "random_string" "this" {
for_each = toset(["health_check"])
length = (7)
lower = true
number = true
special = false
upper = false
}
////////////////////////////////////////////////////////[ VPC NETWORKING ]////////////////////////////////////////////////
## ---------------------------------------------------------------------------------------------------------------------#
# Create our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_vpc" "this" {
cidr_block = var.app["cidr_block"]
instance_tenancy = "default"
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "${var.app["brand"]}-vpc"
Owner = "${var.app["admin_email"]}"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create subnets for each AZ in our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_subnet" "this" {
for_each = data.aws_availability_zone.all
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = cidrsubnet(aws_vpc.this.cidr_block, 4, var.az_number[each.value.name_suffix])
map_public_ip_on_launch = true
tags = {
Name = "${var.app["brand"]}-subnet"
Owner = "${var.app["admin_email"]}"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create RDS subnet group in our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_db_subnet_group" "this" {
name = "${var.app["brand"]}-db-subnet"
description = "${var.app["brand"]} RDS Subnet"
subnet_ids = values(aws_subnet.this).*.id
tags = {
Name = "${var.app["brand"]}-db-subnet"
Owner = "${var.app["admin_email"]}"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create internet gateway in our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
tags = {
Name = "${var.app["brand"]}-igw"
Owner = "${var.app["admin_email"]}"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create route table in our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_route" "this" {
route_table_id = aws_vpc.this.main_route_table_id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.id
}
## ---------------------------------------------------------------------------------------------------------------------#
# Assign AZ subnets to route table in our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_route_table_association" "this" {
for_each = aws_subnet.this
subnet_id = aws_subnet.this[each.key].id
route_table_id = aws_vpc.this.main_route_table_id
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create DHCP options in our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_vpc_dhcp_options" "this" {
domain_name = "${data.aws_region.current.name}.compute.internal"
domain_name_servers = ["AmazonProvidedDNS"]
tags = {
Name = "${var.app["brand"]}-dhcp"
Owner = "${var.app["admin_email"]}"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Assign DHCP options to our dedicated VPC
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_vpc_dhcp_options_association" "this" {
vpc_id = aws_vpc.this.id
dhcp_options_id = aws_vpc_dhcp_options.this.id
}
////////////////////////////////////////////////////[ SNS SUBSCRIPTION TOPIC ]////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create SNS topic and email subscription (confirm email right after resource creation)
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_sns_topic" "default" {
name = "${var.app["brand"]}-email-alerts"
}
resource "aws_sns_topic_subscription" "default" {
topic_arn = aws_sns_topic.default.arn
protocol = "email"
endpoint = var.app["admin_email"]
}
///////////////////////////////////////////////////////[ SECURITY GROUPS ]////////////////////////////////////////////////
## ---------------------------------------------------------------------------------------------------------------------#
# Create Security Groups
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_security_group" "this" {
for_each = local.security_group
name = "${var.app["brand"]}-${each.key}"
description = "${each.key} security group"
vpc_id = aws_vpc.this.id
tags = {
Name = "${var.app["brand"]}-${each.key}"
Owner = "${var.app["admin_email"]}"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create Security Rules for Security Groups
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_security_group_rule" "this" {
for_each = local.security_rule
type = lookup(each.value, "type", null)
description = lookup(each.value, "description", null)
from_port = lookup(each.value, "from_port", null)
to_port = lookup(each.value, "to_port", null)
protocol = lookup(each.value, "protocol", null)
cidr_blocks = lookup(each.value, "cidr_blocks", null)
source_security_group_id = lookup(each.value, "source_security_group_id", null)
security_group_id = each.value.security_group_id
}
///////////////////////////////////////////////////[ AWS CERTIFICATE MANAGER ]////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create and validate ssl certificate for domain and subdomains
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_acm_certificate" "default" {
domain_name = "${var.app["domain"]}"
subject_alternative_names = ["*.${var.app["domain"]}"]
validation_method = "EMAIL"
lifecycle {
create_before_destroy = true
}
}
resource "aws_acm_certificate_validation" "default" {
certificate_arn = aws_acm_certificate.default.arn
}
////////////////////////////////////////////////////////[ CODECOMMIT ]////////////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Setup Git Global user information
# # ---------------------------------------------------------------------------------------------------------------------#
resource "null_resource" "git_user_setup" {
provisioner "local-exec" {
interpreter = ["/bin/bash", "-c"]
command = <<EOF
git config --global user.email "${var.app["git_user_email"]}"
git config --global user.name "${var.app["git_user_name"]}"
EOF
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CodeCommit repository for application code
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_codecommit_repository" "app" {
repository_name = var.app["domain"]
description = "Ghost code for ${var.app["domain"]}"
tags = {
Name = "${var.app["brand"]}-${var.app["domain"]}"
Owner = "${var.app["admin_email"]}"
}
provisioner "local-exec" {
interpreter = ["/bin/bash", "-c"]
command = <<EOF
git clone ${var.app["source"]} /tmp/ghost
cd /tmp/ghost
git remote add origin codecommit::${data.aws_region.current.name}://${aws_codecommit_repository.app.repository_name}
git branch -m main
git push codecommit::${data.aws_region.current.name}://${aws_codecommit_repository.app.repository_name} main
rm -rf /tmp/ghost
EOF
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CodeCommit repository for services configuration
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_codecommit_repository" "services" {
repository_name = "${var.app["brand"]}-services-config"
description = "EC2 linux and services configurations"
tags = {
Name = "${var.app["brand"]}-services-config"
Owner = "${var.app["admin_email"]}"
}
provisioner "local-exec" {
interpreter = ["/bin/bash", "-c"]
command = <<EOF
cd ${abspath(path.root)}/services/nginx
git init
git commit --allow-empty -m "main branch"
git branch -m main
git push codecommit::${data.aws_region.current.name}://${aws_codecommit_repository.services.repository_name} main
git branch -m nginx_frontend
git add .
git commit -m "nginx_ec2_config"
git push codecommit::${data.aws_region.current.name}://${aws_codecommit_repository.services.repository_name} nginx_frontend
git branch -m nginx_staging
git push codecommit::${data.aws_region.current.name}://${aws_codecommit_repository.services.repository_name} nginx_staging
rm -rf .git
EOF
}
}
////////////////////////////////////////////////////////[ CLOUDFRONT ]////////////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudFront distribution with S3 origin
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudfront_origin_access_identity" "this" {
comment = "CloudFront origin access identity"
}
resource "aws_cloudfront_distribution" "this" {
enabled = true
is_ipv6_enabled = true
web_acl_id = aws_wafv2_web_acl.this.arn
price_class = "PriceClass_100"
comment = "${var.app["domain"]} assets"
origin {
domain_name = aws_s3_bucket.this["media"].bucket_regional_domain_name
origin_id = "${var.app["domain"]}-media-assets"
s3_origin_config {
origin_access_identity = aws_cloudfront_origin_access_identity.this.cloudfront_access_identity_path
}
custom_header {
name = "X-X2f1-Header"
value = random_uuid.this.result
}
}
default_cache_behavior {
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
target_origin_id = "${var.app["domain"]}-media-assets"
origin_request_policy_id = data.aws_cloudfront_origin_request_policy.s3.id
cache_policy_id = data.aws_cloudfront_cache_policy.s3.id
viewer_protocol_policy = "https-only"
}
logging_config {
include_cookies = false
bucket = aws_s3_bucket.this["system"].bucket_domain_name
prefix = "${var.app["brand"]}-cloudfront-logs"
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
cloudfront_default_certificate = true
minimum_protocol_version = "TLSv1.2_2021"
}
tags = {
Name = "${var.app["brand"]}-cloudfront-production"
Owner = "${var.app["admin_email"]}"
}
}
/////////////////////////////////////////////////////[ EC2 INSTANCE PROFILE ]/////////////////////////////////////////////
## ---------------------------------------------------------------------------------------------------------------------#
# Create EC2 service role
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_iam_role" "ec2" {
for_each = var.ec2
name = "${var.app["brand"]}-EC2InstanceRole-${each.key}-${data.aws_region.current.name}"
description = "Allows EC2 instances to call AWS services on your behalf"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
## ---------------------------------------------------------------------------------------------------------------------#
# Attach policies to EC2 service role
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_iam_role_policy_attachment" "ec2" {
for_each = { for policy in [ for role,policy in setproduct(keys(var.ec2),var.ec2_instance_profile_policy): { role = policy[0] , policy = policy[1]} ] : "${policy.role}-${policy.policy}" => policy }
role = aws_iam_role.ec2[each.value.role].name
policy_arn = each.value.policy
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create inline policy for EC2 service role to publish sns message
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_iam_role_policy" "sns_publish" {
for_each = var.ec2
name = "EC2ProfileSNSPublishPolicy${title(each.key)}"
role = aws_iam_role.ec2[each.key].id
policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Sid = "EC2ProfileSNSPublishPolicy${each.key}",
Effect = "Allow",
Action = [
"sns:Publish"
],
Resource = aws_sns_topic.default.arn
}]
})
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create inline policy for EC2 service role to limit CodeCommit access
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_iam_role_policy" "codecommit_access" {
for_each = var.ec2
name = "PolicyForCodeCommitAccess${title(each.key)}"
role = aws_iam_role.ec2[each.key].id
policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Sid = "codecommitaccessapp${each.key}",
Effect = "Allow",
Action = [
"codecommit:Get*",
"codecommit:List*",
"codecommit:Merge*",
"codecommit:GitPull",
"codecommit:GitPush"
],
Resource = aws_codecommit_repository.app.arn
Condition = {
StringEqualsIfExists = {
"codecommit:References" = [(each.key == "admin" || each.key == "frontend" ? "refs/heads/main" : (each.key == "staging" ? "refs/heads/staging" : "refs/heads/build"))]
}
}
},
{
Sid = "codecommitaccessservices${each.key}",
Effect = "Allow",
Action = [
"codecommit:Get*",
"codecommit:List*",
"codecommit:Describe*",
"codecommit:GitPull"
],
Resource = aws_codecommit_repository.services.arn
}]
})
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create EC2 Instance Profile
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_iam_instance_profile" "ec2" {
for_each = var.ec2
name = "${var.app["brand"]}-EC2InstanceProfile-${each.key}"
role = aws_iam_role.ec2[each.key].name
}
//////////////////////////////////////////////////////////[ S3 BUCKET ]///////////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create S3 bucket
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_s3_bucket" "this" {
for_each = var.s3
bucket = "${var.app["brand"]}-${each.key}-storage"
force_destroy = true
acl = "private"
tags = {
Name = "${var.app["brand"]}-${each.key}-storage"
Owner = "${var.app["admin_email"]}"
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create IAM user for S3 bucket
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_iam_user" "s3" {
name = "${var.app["brand"]}-s3-media-production"
tags = {
Name = "${var.app["brand"]}-s3-media-production"
}
}
resource "aws_iam_access_key" "s3" {
user = aws_iam_user.s3.name
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create policy for CloudFront and S3 user to limit S3 media bucket access
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_s3_bucket_policy" "media" {
bucket = aws_s3_bucket.this["media"].id
policy = jsonencode({
Id = "PolicyForMediaStorageAccess"
Statement = [
{
Action = "s3:GetObject"
Effect = "Allow"
Principal = {
AWS = aws_cloudfront_origin_access_identity.this.iam_arn
}
Resource = [
"${aws_s3_bucket.this["media"].arn}/*.jpg",
"${aws_s3_bucket.this["media"].arn}/*.jpeg",
"${aws_s3_bucket.this["media"].arn}/*.png",
"${aws_s3_bucket.this["media"].arn}/*.gif",
"${aws_s3_bucket.this["media"].arn}/*.webp"
]
},
{
Action = ["s3:PutObject"],
Effect = "Allow"
Principal = {
AWS = [ aws_iam_user.s3.arn ]
}
Resource = [
"${aws_s3_bucket.this["media"].arn}",
"${aws_s3_bucket.this["media"].arn}/*"
]
Condition = {
StringEquals = {
"aws:SourceVpc" = [ aws_vpc.this.id ]
}
}
},
{
Action = ["s3:GetObject", "s3:GetObjectAcl"],
Effect = "Allow"
Principal = {
AWS = [ aws_iam_user.s3.arn ]
}
Resource = [
"${aws_s3_bucket.this["media"].arn}",
"${aws_s3_bucket.this["media"].arn}/*"
]
},
{
Action = ["s3:GetBucketLocation", "s3:ListBucket"],
Effect = "Allow"
Principal = {
AWS = [ aws_iam_user.s3.arn ]
}
Resource = "${aws_s3_bucket.this["media"].arn}"
},
]
Version = "2012-10-17"
})
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create S3 bucket policy for ALB to write access logs
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_s3_bucket_policy" "system" {
bucket = aws_s3_bucket.this["system"].id
policy = jsonencode(
{
Id = "PolicyALBWriteLogs"
Version = "2012-10-17"
Statement = [
{
Action = [
"s3:PutObject"
],
Effect = "Allow"
Resource = "arn:aws:s3:::${aws_s3_bucket.this["system"].id}/${var.app["brand"]}-alb/AWSLogs/${data.aws_caller_identity.current.account_id}/*"
Principal = {
AWS = [
data.aws_elb_service_account.current.arn
]
}
}
]
}
)
}
//////////////////////////////////////////////////////////////[ RDS ]/////////////////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create RDS parameter groups
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_db_parameter_group" "this" {
for_each = toset(var.rds["name"])
name = "${var.app["brand"]}-${each.key}-parameters"
family = "mariadb10.5"
description = "Parameter group for ${var.app["brand"]} ${each.key} database"
tags = {
Name = "${var.app["brand"]}-${each.key}-parameters"
Owner = "${var.app["admin_email"]}"
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create RDS instance
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_db_instance" "this" {
for_each = toset(var.rds["name"])
identifier = "${var.app["brand"]}-${each.key}"
allocated_storage = var.rds["allocated_storage"]
max_allocated_storage = var.rds["max_allocated_storage"]
storage_type = var.rds["storage_type"]
engine = var.rds["engine"]
engine_version = var.rds["engine_version"]
instance_class = (each.key == "staging" ? var.rds["instance_class_staging"] : var.rds["instance_class"])
multi_az = (each.key == "staging" ? "false" : var.rds["multi_az"])
name = "${var.app["brand"]}_${each.key}"
username = var.app["brand"]
password = random_password.this["rds"].result
parameter_group_name = aws_db_parameter_group.this[each.key].id
skip_final_snapshot = var.rds["skip_final_snapshot"]
vpc_security_group_ids = [aws_security_group.this["rds"].id]
db_subnet_group_name = aws_db_subnet_group.this.name
enabled_cloudwatch_logs_exports = [var.rds["enabled_cloudwatch_logs_exports"]]
performance_insights_enabled = var.rds["performance_insights_enabled"]
copy_tags_to_snapshot = var.rds["copy_tags_to_snapshot"]
backup_retention_period = var.rds["backup_retention_period"]
delete_automated_backups = var.rds["delete_automated_backups"]
deletion_protection = var.rds["deletion_protection"]
tags = {
Name = "${var.app["brand"]}-${each.key}"
Owner = "${var.app["admin_email"]}"
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create RDS instance event subscription
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_db_event_subscription" "db_event_subscription" {
name = "${var.app["brand"]}-rds-event-subscription"
sns_topic = aws_sns_topic.default.arn
source_type = "db-instance"
source_ids = [aws_db_instance.this["production"].id]
event_categories = [
"availability",
"deletion",
"failover",
"failure",
"low storage",
"maintenance",
"notification",
"read replica",
"recovery",
"restoration",
"configuration change"
]
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch CPU Utilization metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "rds_cpu" {
alarm_name = "${var.app["brand"]} rds cpu utilization too high"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "CPUUtilization"
namespace = "AWS/RDS"
period = "600"
statistic = "Average"
threshold = "80"
alarm_description = "Average database CPU utilization over last 10 minutes too high"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
dimensions = {
DBInstanceIdentifier = aws_db_instance.this["production"].id
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch Freeable Memory metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "rds_memory" {
alarm_name = "${var.app["brand"]} rds freeable memory too low"
comparison_operator = "LessThanThreshold"
evaluation_periods = "1"
metric_name = "FreeableMemory"
namespace = "AWS/RDS"
period = "600"
statistic = "Average"
threshold = "1.0e+09"
alarm_description = "Average database freeable memory over last 10 minutes too low, performance may suffer"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
dimensions = {
DBInstanceIdentifier = aws_db_instance.this["production"].id
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch Connections Anomaly metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "rds_connections_anomaly" {
alarm_name = "${var.app["brand"]} rds connections anomaly"
comparison_operator = "GreaterThanUpperThreshold"
evaluation_periods = "5"
threshold_metric_id = "e1"
alarm_description = "Database connection count anomaly detected"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
insufficient_data_actions = []
metric_query {
id = "e1"
expression = "ANOMALY_DETECTION_BAND(m1, 2)"
label = "DatabaseConnections (Expected)"
return_data = "true"
}
metric_query {
id = "m1"
return_data = "true"
metric {
metric_name = "DatabaseConnections"
namespace = "AWS/RDS"
period = "600"
stat = "Average"
unit = "Count"
dimensions = {
DBInstanceIdentifier = aws_db_instance.this["production"].id
}
}
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch Max Connections metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "rds_max_connections" {
alarm_name = "${var.app["brand"]} rds connections over last 10 minutes is too high"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "DatabaseConnections"
namespace = "AWS/RDS"
period = "600"
statistic = "Average"
threshold = ceil((80 / 100) * var.max_connection_count[var.rds["instance_class"]])
alarm_description = "Average connections over last 10 minutes is too high"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
dimensions = {
DBInstanceIdentifier = aws_db_instance.this["production"].id
}
}
/////////////////////////////////////////////////[ APPLICATION LOAD BALANCER ]////////////////////////////////////////////
## ---------------------------------------------------------------------------------------------------------------------#
# Create Application Load Balancers
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_lb" "this" {
for_each = var.alb
name = "${var.app["brand"]}-${each.key}-alb"
internal = each.value
load_balancer_type = "application"
drop_invalid_header_fields = true
security_groups = [aws_security_group.this[each.key].id]
subnets = values(aws_subnet.this).*.id
access_logs {
bucket = aws_s3_bucket.this["system"].bucket
prefix = "${var.app["brand"]}-alb"
enabled = true
}
tags = {
Name = "${var.app["brand"]}-${each.key}-alb"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create Target Groups for Load Balancers
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_lb_target_group" "this" {
for_each = var.ec2
name = "${var.app["brand"]}-${each.key}-target"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.this.id
health_check {
path = "/healtz"
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create https:// listener for OUTER Load Balancer - forward to webnode
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_lb_listener" "outerhttps" {
depends_on = [aws_acm_certificate_validation.default]
load_balancer_arn = aws_lb.this["outer"].arn
port = "443"
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-FS-1-2-Res-2020-10"
certificate_arn = aws_acm_certificate.default.arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.this["frontend"].arn
}
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create http:// listener for OUTER Load Balancer - redirect to https://
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_lb_listener" "outerhttp" {
load_balancer_arn = aws_lb.this["outer"].arn
port = "80"
protocol = "HTTP"
default_action {
type = "redirect"
redirect {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch HTTP 5XX metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "httpcode_target_5xx_count" {
alarm_name = "${var.app["brand"]}-http-5xx-errors-from-target"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "HTTPCode_Target_5XX_Count"
namespace = "AWS/ApplicationELB"
period = 300
statistic = "Sum"
threshold = "25"
alarm_description = "HTTPCode 5XX count for frontend instances over 25"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
dimensions = {
TargetGroup = aws_lb_target_group.this["frontend"].arn
LoadBalancer = aws_lb.this["outer"].arn
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch HTTP 5XX metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "httpcode_elb_5xx_count" {
alarm_name = "${var.app["brand"]}-http-5xx-errors-from-loadbalancer"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "HTTPCode_ELB_5XX_Count"
namespace = "AWS/ApplicationELB"
period = 300
statistic = "Sum"
threshold = "25"
alarm_description = "HTTPCode 5XX count for loadbalancer over 25"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
dimensions = {
LoadBalancer = aws_lb.this["outer"].arn
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch RequestCount metrics and email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "alb_rps" {
alarm_name = "${var.app["brand"]}-loadbalancer-rps"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "RequestCount"
namespace = "AWS/ApplicationELB"
period = "120"
statistic = "Sum"
threshold = "5000"
alarm_description = "The number of requests processed over 2 minutes greater than 5000"
alarm_actions = ["${aws_sns_topic.default.arn}"]
ok_actions = ["${aws_sns_topic.default.arn}"]
dimensions = {
LoadBalancer = aws_lb.this["outer"].arn
}
}
/////////////////////////////////////////////////////[ AUTOSCALING CONFIGURATION ]////////////////////////////////////////
# # ---------------------------------------------------------------------------------------------------------------------#
# Create Launch Template for Autoscaling Groups - user_data converted
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_launch_template" "this" {
for_each = var.ec2
name = "${var.app["brand"]}-${each.key}-ltpl"
block_device_mappings {
device_name = "/dev/xvda"
ebs {
volume_size = var.app["volume_size"]
volume_type = "gp3"
}
}
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
}
iam_instance_profile {
name = aws_iam_instance_profile.ec2[each.key].name
}
image_id = data.aws_ami.distro.id
instance_type = each.value
monitoring { enabled = false }
network_interfaces {
associate_public_ip_address = true
security_groups = [aws_security_group.this["ec2"].id]
}
tag_specifications {
resource_type = "instance"
tags = {
Name = "${var.app["brand"]}-${each.key}-ec2"
Owner = "${var.app["admin_email"]}"
}
}
tag_specifications {
resource_type = "volume"
tags = {
Name = "${var.app["brand"]}-${each.key}-ec2"
Owner = "${var.app["admin_email"]}"
}
}
user_data = base64encode(data.template_file.user_data[each.key].rendered)
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create Autoscaling Groups
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_autoscaling_group" "this" {
for_each = var.ec2
name = "${var.app["brand"]}-${each.key}-asg"
vpc_zone_identifier = values(aws_subnet.this).*.id
desired_capacity = var.asg["desired_capacity"]
min_size = var.asg["min_size"]
max_size = var.asg["max_size"]
health_check_grace_period = var.asg["health_check_grace_period"]
health_check_type = var.asg["health_check_type"]
target_group_arns = [aws_lb_target_group.this[each.key].arn]
launch_template {
name = aws_launch_template.this[each.key].name
version = "$Latest"
}
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create Autoscaling groups actions for SNS topic email alerts
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_autoscaling_notification" "this" {
for_each = aws_autoscaling_group.this
group_names = [
aws_autoscaling_group.this[each.key].name
]
notifications = [
"autoscaling:EC2_INSTANCE_LAUNCH",
"autoscaling:EC2_INSTANCE_TERMINATE",
"autoscaling:EC2_INSTANCE_LAUNCH_ERROR",
"autoscaling:EC2_INSTANCE_TERMINATE_ERROR",
]
topic_arn = aws_sns_topic.default.arn
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create Autoscaling policy for scale-out
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_autoscaling_policy" "scaleout" {
for_each = var.ec2
name = "${var.app["brand"]}-${each.key}-asp-out"
scaling_adjustment = 1
adjustment_type = "ChangeInCapacity"
cooldown = 300
autoscaling_group_name = aws_autoscaling_group.this[each.key].name
}
# # ---------------------------------------------------------------------------------------------------------------------#
# Create CloudWatch alarm metric to execute Autoscaling policy for scale-out
# # ---------------------------------------------------------------------------------------------------------------------#
resource "aws_cloudwatch_metric_alarm" "scaleout" {
for_each = var.ec2
alarm_name = "${var.app["brand"]}-${each.key} scale-out alarm"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = var.asp["evaluation_periods"]
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = var.asp["period"]
statistic = "Average"
threshold = var.asp["out_threshold"]
dimensions = {
AutoScalingGroupName = aws_autoscaling_group.this[each.key].name
}
alarm_description = "${each.key} scale-out alarm - CPU exceeds ${var.asp["out_threshold"]} percent"
alarm_actions = [aws_autoscaling_policy.scaleout[each.key].arn]
}
## ---------------------------------------------------------------------------------------------------------------------#
# Create Autoscaling policy for scale-in
## ---------------------------------------------------------------------------------------------------------------------#
resource "aws_autoscaling_policy" "scalein" {
for_each = var.ec2
name = "${var.app["brand"]}-${each.key}-asp-in"
scaling_adjustment = -1
adjustment_type = "ChangeInCapacity"
cooldown = 300
autoscaling_group_name = aws_autoscaling_group.this[each.key].name
}
# # ---------------------------------------------------------------------------------------------------------------------#