-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.tf
628 lines (521 loc) · 22.9 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
/* -------------------------------------------------------------------------- */
/* Task Role */
/* -------------------------------------------------------------------------- */
data "aws_iam_policy_document" "task_assume_role_policy" {
count = var.is_create_iam_role ? 1 : 0
statement {
sid = ""
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "task_role" {
count = var.is_create_iam_role ? 1 : 0
name = format("%s-ecs-task-role", local.name)
assume_role_policy = data.aws_iam_policy_document.task_assume_role_policy[0].json
tags = merge(local.tags, { "Name" = format("%s-ecs-task-role", local.name) })
}
resource "aws_iam_role_policy_attachment" "task_role" {
count = var.is_create_iam_role ? length(var.additional_ecs_task_role_policy_arns) : 0
role = local.task_role_name
policy_arn = var.additional_ecs_task_role_policy_arns[count.index]
}
/* -------------------------------------------------------------------------- */
/* Task Exec Role */
/* -------------------------------------------------------------------------- */
data "aws_iam_policy_document" "task_execution_assume_role_policy" {
count = var.is_create_iam_role ? 1 : 0
statement {
sid = ""
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "task_execution_role" {
count = var.is_create_iam_role ? 1 : 0
name = format("%s-ecs-task-execution-role", local.name)
assume_role_policy = data.aws_iam_policy_document.task_execution_assume_role_policy[0].json
tags = merge(local.tags, { "Name" = format("%s-ecs-task-execution-role", local.name) })
}
resource "aws_iam_role_policy_attachment" "task_execution_role" {
for_each = var.is_create_iam_role ? local.ecs_task_execution_role_policy_arns : []
role = local.task_execution_role_name
policy_arn = each.value
}
/* -------------------------------------------------------------------------- */
/* CloudWatch */
/* -------------------------------------------------------------------------- */
data "aws_iam_policy_document" "cloudwatch_log_group_kms_policy" {
statement {
sid = "AllowCloudWatchToDoCryptography"
actions = [
"kms:Encrypt*",
"kms:Decrypt*",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:Describe*"
]
resources = ["*"]
principals {
type = "Service"
identifiers = tolist([format("logs.%s.amazonaws.com", data.aws_region.this.name)])
}
condition {
test = "ArnEquals"
variable = "kms:EncryptionContext:aws:logs:arn"
values = [format("arn:aws:logs:%s:%s:log-group:%s", data.aws_region.this.name, data.aws_caller_identity.this.account_id, local.log_group_name)]
}
}
}
module "cloudwatch_log_group_kms" {
count = var.is_create_cloudwatch_log_group && var.is_create_default_kms && var.cloudwatch_log_group_kms_key_arn == null ? 1 : 0
source = "oozou/kms-key/aws"
version = "1.0.0"
prefix = var.prefix
environment = var.environment
name = format("%s-log-group", var.name)
key_type = "service"
append_random_suffix = true
description = format("Secure Secrets Manager's service secrets for service %s", local.name)
additional_policies = [data.aws_iam_policy_document.cloudwatch_log_group_kms_policy.json]
tags = merge(local.tags, { "Name" : format("%s-log-group", local.name) })
}
resource "aws_cloudwatch_log_group" "this" {
count = var.is_create_cloudwatch_log_group ? 1 : 0
name = local.log_group_name
retention_in_days = var.cloudwatch_log_retention_in_days
kms_key_id = local.cloudwatch_log_group_kms_key_arn
tags = merge(local.tags, { "Name" = local.log_group_name })
}
/* -------------------------------------------------------------------------- */
/* Load Balancer */
/* -------------------------------------------------------------------------- */
resource "aws_lb_target_group" "this" {
for_each = var.alb_target_group
name = format("%s-tg", substr(format("%s", replace(each.key, "_", "-")), 0, min(29, length(format("%s", replace(each.key, "_", "-"))))))
port = lookup(each.value, "port", null)
protocol = lookup(each.value, "protocol", null)
vpc_id = var.vpc_id
target_type = lookup(each.value, "target_type", "ip")
deregistration_delay = var.target_group_deregistration_delay
health_check {
enabled = lookup(each.value.health_check, "enabled", null)
interval = lookup(each.value.health_check, "interval", null)
path = lookup(each.value.health_check, "path", null)
timeout = lookup(each.value.health_check, "timeout", null)
healthy_threshold = lookup(each.value.health_check, "healthy_threshold", null)
unhealthy_threshold = lookup(each.value.health_check, "unhealthy_threshold", null)
matcher = lookup(each.value.health_check, "matcher", null)
port = lookup(each.value.health_check, "port", null)
}
dynamic "stickiness" {
for_each = lookup(each.value, "stickiness", null) == null ? [] : [true]
content {
enabled = lookup(each.value.stickiness, "enabled", null)
type = lookup(each.value.stickiness, "type", null)
cookie_name = lookup(each.value.stickiness, "cookie_name", null)
cookie_duration = lookup(each.value.stickiness, "cookie_duration", null)
}
}
tags = merge(local.tags, { "Name" = format("%s-tg", substr(format("%s", replace(each.key, "_", "-")), 0, min(29, length(format("%s", replace(each.key, "_", "-")))))) })
}
/* ------------------------------ Listener Rule ----------------------------- */
resource "aws_lb_listener_rule" "this" {
count = length(var.alb_listener_rules)
listener_arn = var.alb_listener_arn
priority = lookup(var.alb_listener_rules[count.index], "alb_priority", null)
dynamic "action" {
for_each = [
# for action_rule in var.additional_alb_rule[count.index].actions :
for action_rule in lookup(var.alb_listener_rules[count.index], "actions") :
action_rule
if action_rule.type == "forward"
]
content {
type = action.value["type"]
target_group_arn = aws_lb_target_group.this[lookup(var.alb_listener_rules[count.index], "target_group")].arn
}
}
# redirect actions
dynamic "action" {
for_each = [
# for action_rule in var.additional_alb_rule[count.index].actions :
for action_rule in lookup(var.alb_listener_rules[count.index], "actions") :
action_rule
if action_rule.type == "redirect"
]
content {
type = action.value["type"]
redirect {
host = lookup(action.value, "host", null)
path = lookup(action.value, "path", null)
port = lookup(action.value, "port", null)
protocol = lookup(action.value, "protocol", null)
query = lookup(action.value, "query", null)
status_code = action.value["status_code"]
}
}
}
# Path Pattern condition
dynamic "condition" {
for_each = length(lookup(var.alb_listener_rules[count.index], "alb_paths", [])) > 0 ? [true] : []
content {
path_pattern {
values = lookup(var.alb_listener_rules[count.index], "alb_paths")
}
}
}
# Host header condition
dynamic "condition" {
for_each = lookup(var.alb_listener_rules[count.index], "alb_host_header", null) == null ? [] : [true]
content {
host_header {
values = [lookup(var.alb_listener_rules[count.index], "alb_host_header")]
}
}
}
# http header condition
dynamic "condition" {
for_each = var.custom_header_token == "" ? [] : [true]
content {
http_header {
http_header_name = "custom-header-token" # Match value within cloudfront module
values = [var.custom_header_token]
}
}
}
# Query string condition
dynamic "condition" {
for_each = length(lookup(var.alb_listener_rules[count.index], "alb_query_strings", [])) > 0 ? [true] : []
content {
dynamic "query_string" {
for_each = [
for query_string in var.alb_listener_rules[count.index].alb_query_strings :
query_string
]
content {
key = lookup(query_string.value, "key", null)
value = query_string.value["value"]
}
}
}
}
tags = local.tags
}
/* -------------------------------------------------------------------------- */
/* Secret */
/* -------------------------------------------------------------------------- */
module "secret_kms_key" {
source = "oozou/kms-key/aws"
version = "1.0.0"
prefix = var.prefix
environment = var.environment
name = format("%s-ecs", var.name)
key_type = "service"
append_random_suffix = true
description = format("Secure Secrets Manager's service secrets for service %s", local.name)
service_key_info = {
aws_service_names = tolist([format("secretsmanager.%s.amazonaws.com", data.aws_region.this.name)])
caller_account_ids = tolist([data.aws_caller_identity.this.account_id])
}
tags = merge(local.tags, { "Name" : format("%s-ecs", local.name) })
}
resource "random_string" "service_secret_random_suffix" {
for_each = var.container
length = 5
special = false
}
/* -------------------------------------------------------------------------- */
/* Secret */
/* -------------------------------------------------------------------------- */
resource "aws_secretsmanager_secret" "this" {
for_each = var.container
name = "${each.value.name}/${random_string.service_secret_random_suffix[each.key].result}"
description = "Secret for service ${local.name}"
kms_key_id = module.secret_kms_key.key_arn
tags = merge({ Name = "${each.value.name}/${random_string.service_secret_random_suffix[each.key].result}" }, local.tags)
}
resource "aws_secretsmanager_secret_version" "this" {
for_each = var.container
secret_id = aws_secretsmanager_secret.this[each.key].id
secret_string = jsonencode(try(var.secret_variables[each.key], {}))
}
# We add a policy to the ECS Task Execution role so that ECS can pull secrets from SecretsManager and
# inject them as environment variables in the service
resource "aws_iam_role_policy" "task_execution_role_access_secret" {
# count = var.is_create_iam_role && length(var.secret_variables) > 0 ? 1 : 0
for_each = var.container
name = "${each.value.name}-ecs-task-execution-secrets"
role = local.task_execution_role_id
policy = <<EOF
{
"Statement": [
{
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": ${jsonencode(format("%s/*", split("/", aws_secretsmanager_secret.this[each.key].arn)[0]))}
}
]
}
EOF
}
/* -------------------------------------------------------------------------- */
/* ECS Task Definition */
/* -------------------------------------------------------------------------- */
resource "aws_ecs_task_definition" "this" {
family = local.name
network_mode = "awsvpc"
requires_compatibilities = var.capacity_provider_strategy == null ? ["FARGATE"] : ["EC2"]
cpu = var.task_cpu
memory = var.task_memory
execution_role_arn = local.task_execution_role_arn
task_role_arn = local.task_role_arn
container_definitions = jsonencode(local.container_task_definitions)
dynamic "volume" {
for_each = local.volumes
content {
host_path = lookup(volume.value, "host_path", null)
name = volume.value.name
dynamic "efs_volume_configuration" {
for_each = lookup(volume.value, "efs_volume_configuration", [])
content {
file_system_id = lookup(efs_volume_configuration.value, "file_system_id", null)
root_directory = lookup(efs_volume_configuration.value, "root_directory", null)
transit_encryption = lookup(efs_volume_configuration.value, "transit_encryption", null)
transit_encryption_port = lookup(efs_volume_configuration.value, "transit_encryption_port", null)
dynamic "authorization_config" {
for_each = lookup(efs_volume_configuration.value, "authorization_config", [])
content {
access_point_id = lookup(authorization_config.value, "access_point_id", null)
iam = lookup(authorization_config.value, "iam", null)
}
}
}
}
}
}
dynamic "volume" {
for_each = var.is_application_scratch_volume_enabled ? [true] : []
content {
name = "application_scratch"
}
}
tags = merge(local.tags, { "Name" = local.name })
}
/* -------------------------------------------------------------------------- */
/* ECS Service */
/* -------------------------------------------------------------------------- */
resource "aws_service_discovery_service" "service" {
name = local.name
dns_config {
namespace_id = var.service_discovery_namespace
dns_records {
ttl = 10
type = "A"
}
routing_policy = "MULTIVALUE"
}
health_check_custom_config {
failure_threshold = 1
}
}
resource "aws_ecs_service" "this" {
name = format("%s", local.name)
cluster = local.ecs_cluster_arn
task_definition = aws_ecs_task_definition.this.arn
desired_count = var.service_count
enable_execute_command = var.is_enable_execute_command
enable_ecs_managed_tags = true
launch_type = var.capacity_provider_strategy == null ? "FARGATE" : null
propagate_tags = var.propagate_tags
network_configuration {
security_groups = var.security_groups
subnets = var.application_subnet_ids
}
dynamic "ordered_placement_strategy" {
for_each = var.capacity_provider_strategy == null ? [] : var.ordered_placement_strategy
content {
type = ordered_placement_strategy.value.type
field = ordered_placement_strategy.value.field
}
}
service_registries {
registry_arn = aws_service_discovery_service.service.arn
container_name = local.name
}
dynamic "capacity_provider_strategy" {
for_each = var.capacity_provider_strategy == null ? [] : [true]
content {
base = var.capacity_provider_strategy.base
capacity_provider = var.capacity_provider_strategy.capacity_provider
weight = var.capacity_provider_strategy.weight
}
}
deployment_circuit_breaker {
enable = var.deployment_circuit_breaker.enable
rollback = var.deployment_circuit_breaker.rollback
}
dynamic "load_balancer" {
for_each = var.alb_target_group
content {
target_group_arn = aws_lb_target_group.this[load_balancer.key].arn
container_name = local.name
container_port = load_balancer.value.port
}
}
lifecycle {
ignore_changes = [
task_definition,
desired_count
]
}
tags = merge(local.tags, { Name = format("%s", local.name) })
}
/* -------------------------------------------------------------------------- */
/* Auto Scaling Target */
/* -------------------------------------------------------------------------- */
resource "aws_appautoscaling_target" "this" {
count = local.is_created_aws_appautoscaling_target ? 1 : 0
max_capacity = try(
var.target_tracking_configuration.capacity.max_capacity,
var.step_scaling_configuration.capacity.max_capacity
)
min_capacity = try(
var.target_tracking_configuration.capacity.min_capacity,
var.step_scaling_configuration.capacity.min_capacity
)
resource_id = format("service/%s/%s", var.ecs_cluster_name, local.name)
scalable_dimension = "ecs:service:DesiredCount"
service_namespace = "ecs"
}
/* -------------------------------------------------------------------------- */
/* Auto Scaling Policy */
/* -------------------------------------------------------------------------- */
resource "aws_appautoscaling_policy" "target_tracking_scaling_policies" {
count = local.is_target_tracking_scaling ? 1 : 0
depends_on = [aws_appautoscaling_target.this[0]]
name = format("%s-%s-scaling-policy", local.name, var.target_tracking_configuration["name"])
resource_id = aws_appautoscaling_target.this[0].resource_id
scalable_dimension = aws_appautoscaling_target.this[0].scalable_dimension
service_namespace = aws_appautoscaling_target.this[0].service_namespace
policy_type = "TargetTrackingScaling"
target_tracking_scaling_policy_configuration {
target_value = lookup(var.target_tracking_configuration["scaling_behaviors"], "target_value", null)
scale_in_cooldown = lookup(var.target_tracking_configuration["scaling_behaviors"], "scale_in_cooldown", 180)
scale_out_cooldown = lookup(var.target_tracking_configuration["scaling_behaviors"], "scale_out_cooldown", 60)
dynamic "predefined_metric_specification" {
for_each = local.is_contain_predefined_metric ? [true] : []
iterator = _null
content {
predefined_metric_type = lookup(var.target_tracking_configuration["scaling_behaviors"], "predefined_metric_type", null)
}
}
dynamic "customized_metric_specification" {
for_each = !local.is_contain_predefined_metric ? [true] : []
iterator = _null
content {
dynamic "metrics" {
for_each = { for k, v in lookup(var.target_tracking_configuration["scaling_behaviors"], "custom_metrics", {}) : k => v if lookup(v, "expression", null) == null }
iterator = custom_metric
content {
id = lookup(custom_metric.value, "id", null)
label = lookup(custom_metric.value, "label", replace("_", "-", custom_metric.key))
expression = lookup(custom_metric.value, "expression", null)
return_data = lookup(custom_metric.value, "return_data", true)
metric_stat {
stat = lookup(lookup(custom_metric.value, "metric_stat", {}), "stat", "")
metric {
metric_name = lookup(lookup(custom_metric.value, "metric_stat", {}), "metric_name", null)
namespace = lookup(lookup(custom_metric.value, "metric_stat", {}), "namespace", null)
dynamic "dimensions" {
for_each = lookup(lookup(custom_metric.value, "metric_stat", {}), "dimensions", [])
iterator = dimension
content {
name = lookup(dimension.value, "name", null)
value = lookup(dimension.value, "value", null)
}
}
}
}
}
}
dynamic "metrics" {
for_each = { for k, v in lookup(var.target_tracking_configuration["scaling_behaviors"], "custom_metrics", {}) : k => v if lookup(v, "expression", null) != null }
iterator = custom_metric
content {
id = lookup(custom_metric.value, "id", null)
label = lookup(custom_metric.value, "label", replace("_", "-", custom_metric.key))
expression = lookup(custom_metric.value, "expression", null)
return_data = lookup(custom_metric.value, "return_data", true)
}
}
}
}
}
}
resource "aws_appautoscaling_policy" "step_scaling_policies" {
for_each = try(var.step_scaling_configuration.policy_type, null) == "StepScaling" ? var.step_scaling_configuration["scaling_behaviors"] : {}
depends_on = [aws_appautoscaling_target.this[0]]
name = format("%s-%s-scaling-policy", local.name, replace(each.key, "_", "-"))
resource_id = aws_appautoscaling_target.this[0].resource_id
scalable_dimension = aws_appautoscaling_target.this[0].scalable_dimension
service_namespace = aws_appautoscaling_target.this[0].service_namespace
policy_type = "StepScaling"
step_scaling_policy_configuration {
adjustment_type = "ChangeInCapacity"
cooldown = lookup(each.value, "cooldown", null)
metric_aggregation_type = lookup(each.value, "statistic", null)
dynamic "step_adjustment" {
for_each = lookup(each.value, "step_adjustment", [])
iterator = step_adjustment
content {
metric_interval_lower_bound = lookup(step_adjustment.value, "metric_interval_lower_bound", null)
metric_interval_upper_bound = lookup(step_adjustment.value, "metric_interval_upper_bound", null)
scaling_adjustment = lookup(step_adjustment.value, "scaling_adjustment", null)
}
}
}
}
module "step_alarm" {
source = "oozou/cloudwatch-alarm/aws"
version = "1.0.0"
for_each = try(var.step_scaling_configuration.policy_type, null) == "StepScaling" ? var.step_scaling_configuration["scaling_behaviors"] : {}
depends_on = [aws_appautoscaling_target.this[0]]
prefix = var.prefix
environment = var.environment
name = format("%s-scaling-policy", replace(each.key, "_", "-"))
alarm_description = format(
"%s's %s %s %s in period %ss with %s datapoint",
lookup(each.value, "metric_name", "custom-metric"),
lookup(each.value, "statistic", "null"),
lookup(each.value, "comparison_operator", "null"),
lookup(each.value, "threshold", "null"),
lookup(each.value, "period", "null"),
lookup(each.value, "evaluation_periods", "null")
)
comparison_operator = local.comparison_operators[lookup(each.value, "comparison_operator", null)]
evaluation_periods = lookup(each.value, "evaluation_periods", null)
metric_name = lookup(each.value, "metric_name", null)
metric_query = lookup(each.value, "metric_query", [])
namespace = lookup(each.value, "namespace", null)
period = lookup(each.value, "period", null)
statistic = lookup(each.value, "metric_query", null) == null ? lookup(each.value, "statistic", null) : null
threshold = lookup(each.value, "threshold", null)
dimensions = lookup(each.value, "metric_query", null) == null ? {
ClusterName = var.ecs_cluster_name
ServiceName = local.name
} : null
alarm_actions = concat(
[aws_appautoscaling_policy.step_scaling_policies[each.key].arn],
lookup(each.value, "alarm_actions", lookup(var.step_scaling_configuration, "default_alarm_actions", []))
)
tags = local.tags
}