-
Notifications
You must be signed in to change notification settings - Fork 62
/
main.tf
581 lines (474 loc) · 16.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
locals {
awslogs_group = var.logs_cloudwatch_group == "" ? "/ecs/${var.environment}/${var.name}" : var.logs_cloudwatch_group
target_container_name = var.target_container_name == "" ? "${var.name}-${var.environment}" : var.target_container_name
cloudwatch_alarm_name = var.cloudwatch_alarm_name == "" ? "${var.name}-${var.environment}" : var.cloudwatch_alarm_name
# for each target group, allow ingress from the alb to ecs container port
lb_ingress_container_ports = distinct(
[
for lb_target_group in var.lb_target_groups : lb_target_group.container_port
]
)
# for each target group, allow ingress from the alb to ecs healthcheck port
# if it doesn't collide with the container ports
lb_ingress_container_health_check_ports = tolist(
setsubtract(
[
for lb_target_group in var.lb_target_groups : lb_target_group.container_health_check_port
],
local.lb_ingress_container_ports,
)
)
# base64 encoded version of the helloworld go app
base64_encode_helloworld = base64encode(file("${path.module}/examples/helloworld.go"))
# default container definition to be used with the helloworld go app included
# in this repo. It currently supports 2 HTTP listeners configured on
# environment variables PORT1 and PORT2 and simple JSON requests logs
default_container_definitions = jsonencode(
[
{
name = local.target_container_name
image = var.container_image
cpu = var.fargate_task_cpu
memory = var.fargate_task_memory
essential = true
portMappings = [
{
containerPort = element(var.hello_world_container_ports, 0)
hostPort = element(var.hello_world_container_ports, 0)
protocol = "tcp"
},
{
containerPort = element(var.hello_world_container_ports, 1)
hostPort = element(var.hello_world_container_ports, 1)
protocol = "tcp"
}
]
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = local.awslogs_group
"awslogs-region" = data.aws_region.current.name
"awslogs-stream-prefix" = "helloworld"
}
}
environment = [
{
"name" : "PORT1",
"value" : tostring(element(var.hello_world_container_ports, 0))
},
{
"name" : "PORT2",
"value" : tostring(element(var.hello_world_container_ports, 1))
}
]
mountPoints = []
volumesFrom = []
entryPoint = [
"/bin/sh", "-c",
"echo '${local.base64_encode_helloworld}' | base64 -d > helloworld.go && go run helloworld.go"
]
}
]
)
}
#
# CloudWatch
#
resource "aws_cloudwatch_log_group" "main" {
name = local.awslogs_group
retention_in_days = var.logs_cloudwatch_retention
kms_key_id = var.kms_key_id
}
resource "aws_cloudwatch_metric_alarm" "alarm_cpu" {
count = var.cloudwatch_alarm_cpu_enable ? 1 : 0
alarm_name = "${local.cloudwatch_alarm_name}-cpu"
alarm_description = "Monitors ECS CPU Utilization"
alarm_actions = var.cloudwatch_alarm_actions
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "2"
metric_name = "CPUUtilization"
namespace = "AWS/ECS"
period = "120"
statistic = "Average"
threshold = var.cloudwatch_alarm_cpu_threshold
dimensions = {
"ClusterName" = var.ecs_cluster.name
"ServiceName" = aws_ecs_service.main.name
}
}
resource "aws_cloudwatch_metric_alarm" "alarm_mem" {
count = var.cloudwatch_alarm_mem_enable ? 1 : 0
alarm_name = "${local.cloudwatch_alarm_name}-mem"
alarm_description = "Monitors ECS memory Utilization"
alarm_actions = var.cloudwatch_alarm_actions
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "2"
metric_name = "MemoryUtilization"
namespace = "AWS/ECS"
period = "120"
statistic = "Average"
threshold = var.cloudwatch_alarm_mem_threshold
dimensions = {
"ClusterName" = var.ecs_cluster.name
"ServiceName" = aws_ecs_service.main.name
}
}
#
# SG - ECS
#
resource "aws_security_group" "ecs_sg" {
count = var.manage_ecs_security_group ? 1 : 0
name = "ecs-${var.name}-${var.environment}"
description = "${var.name}-${var.environment} container security group"
vpc_id = var.ecs_vpc_id
}
resource "aws_security_group_rule" "app_ecs_allow_outbound" {
count = var.manage_ecs_security_group ? 1 : 0
description = "All outbound"
security_group_id = aws_security_group.ecs_sg[0].id
type = "egress"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
resource "aws_security_group_rule" "app_ecs_allow_https_from_alb" {
# if we have an alb, then create security group rules for the container
# ports
count = var.manage_ecs_security_group && var.associate_alb ? length(local.lb_ingress_container_ports) : 0
description = "Allow in ALB"
security_group_id = aws_security_group.ecs_sg[0].id
type = "ingress"
from_port = element(local.lb_ingress_container_ports, count.index)
to_port = element(local.lb_ingress_container_ports, count.index)
protocol = "tcp"
source_security_group_id = var.alb_security_group
}
resource "aws_security_group_rule" "app_ecs_allow_health_check_from_alb" {
# if we have an alb, then create security group rules for the container
# health check ports
count = var.manage_ecs_security_group && var.associate_alb ? length(local.lb_ingress_container_health_check_ports) : 0
description = "Allow in health check from ALB"
security_group_id = aws_security_group.ecs_sg[0].id
type = "ingress"
from_port = element(local.lb_ingress_container_health_check_ports, count.index)
to_port = element(local.lb_ingress_container_health_check_ports, count.index)
protocol = "tcp"
source_security_group_id = var.alb_security_group
}
resource "aws_security_group_rule" "app_ecs_allow_tcp_from_nlb" {
count = var.manage_ecs_security_group && var.associate_nlb ? length(local.lb_ingress_container_ports) : 0
description = "Allow in NLB"
security_group_id = aws_security_group.ecs_sg[0].id
type = "ingress"
from_port = element(local.lb_ingress_container_ports, count.index)
to_port = element(local.lb_ingress_container_ports, count.index)
protocol = "tcp"
cidr_blocks = var.nlb_subnet_cidr_blocks
}
resource "aws_security_group_rule" "app_ecs_allow_health_check_from_nlb" {
count = var.manage_ecs_security_group && var.associate_nlb ? length(local.lb_ingress_container_health_check_ports) : 0
description = "Allow in health check from NLB"
security_group_id = aws_security_group.ecs_sg[0].id
type = "ingress"
from_port = element(local.lb_ingress_container_health_check_ports, count.index)
to_port = element(local.lb_ingress_container_health_check_ports, count.index)
protocol = "tcp"
cidr_blocks = var.nlb_subnet_cidr_blocks
}
#
# IAM - instance (optional)
#
data "aws_iam_policy_document" "instance_role_policy_doc" {
count = var.ecs_instance_role != "" ? 1 : 0
statement {
actions = [
"ecs:DeregisterContainerInstance",
"ecs:RegisterContainerInstance",
"ecs:Submit*",
]
resources = [var.ecs_cluster.arn]
}
statement {
actions = [
"ecs:UpdateContainerInstancesState",
]
resources = ["*"]
condition {
test = "StringEquals"
variable = "ecs:cluster"
values = [var.ecs_cluster.arn]
}
}
statement {
actions = [
"ecs:DiscoverPollEndpoint",
"ecs:Poll",
"ecs:StartTelemetrySession",
]
resources = ["*"]
}
statement {
actions = [
"logs:CreateLogStream",
"logs:PutLogEvents",
]
resources = ["${aws_cloudwatch_log_group.main.arn}:*"]
}
statement {
actions = [
"ecr:GetAuthorizationToken",
]
resources = ["*"]
}
statement {
actions = [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
]
resources = var.ecr_repo_arns
}
}
resource "aws_iam_role_policy" "instance_role_policy" {
count = var.ecs_instance_role != "" ? 1 : 0
name = "${var.ecs_instance_role}-policy"
role = var.ecs_instance_role
policy = data.aws_iam_policy_document.instance_role_policy_doc[0].json
}
#
# IAM - task
#
data "aws_iam_policy_document" "ecs_assume_role_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
data "aws_iam_policy_document" "task_execution_role_policy_doc" {
statement {
actions = [
"logs:CreateLogStream",
"logs:PutLogEvents",
]
resources = ["${aws_cloudwatch_log_group.main.arn}:*"]
}
statement {
actions = [
"ecr:GetAuthorizationToken",
]
resources = ["*"]
}
statement {
actions = [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
]
resources = var.ecr_repo_arns
}
}
resource "aws_iam_role" "task_role" {
name = "ecs-task-role-${var.name}-${var.environment}"
assume_role_policy = data.aws_iam_policy_document.ecs_assume_role_policy.json
}
resource "aws_iam_role" "task_execution_role" {
# if ecs_use_fargate is True, create aws_iam_role resource
# if ecs_use_fargate is False, check whether value of ec2_create_task_execution_role is True/False.
# if True, set to 1 creating the resource, if False, set to 0, not creating the resource
count = var.ecs_use_fargate ? 1 : var.ec2_create_task_execution_role ? 1 : 0
name = "ecs-task-execution-role-${var.name}-${var.environment}"
assume_role_policy = data.aws_iam_policy_document.ecs_assume_role_policy.json
}
resource "aws_iam_role_policy" "task_execution_role_policy" {
# if ecs_use_fargate is True, create aws_iam_role_policy resource
# if ecs_use_fargate is False, check whether value of ec2_create_task_execution_role is True/False.
# if True, set to 1 creating the resource, if False, set to 0, not creating the resource
count = var.ecs_use_fargate ? 1 : var.ec2_create_task_execution_role ? 1 : 0
name = "${aws_iam_role.task_execution_role[0].name}-policy"
role = aws_iam_role.task_execution_role[0].name
policy = data.aws_iam_policy_document.task_execution_role_policy_doc.json
}
#
# ECS Exec
#
data "aws_iam_policy_document" "task_role_ecs_exec" {
count = var.ecs_exec_enable ? 1 : 0
statement {
sid = "AllowECSExec"
effect = "Allow"
actions = [
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
]
resources = ["*"]
}
statement {
sid = "AllowDescribeLogGroups"
actions = [
"logs:DescribeLogGroups",
]
resources = ["*"]
}
statement {
sid = "AllowECSExecLogging"
actions = [
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
]
resources = ["${aws_cloudwatch_log_group.main.arn}:*"]
}
}
resource "aws_iam_policy" "task_role_ecs_exec" {
count = var.ecs_exec_enable ? 1 : 0
name = "${aws_iam_role.task_role.name}-ecs-exec"
description = "Allow ECS Exec with Cloudwatch logging when attached to an ECS task role"
policy = join("", data.aws_iam_policy_document.task_role_ecs_exec.*.json)
}
resource "aws_iam_role_policy_attachment" "task_role_ecs_exec" {
count = var.ecs_exec_enable ? 1 : 0
role = join("", aws_iam_role.task_role.*.name)
policy_arn = join("", aws_iam_policy.task_role_ecs_exec.*.arn)
}
#
# ECS
#
data "aws_region" "current" {
}
# Create a task definition with a golang image so the ecs service can be
# tested. We expect deployments will manage the future container definitions.
resource "aws_ecs_task_definition" "main" {
family = "${var.name}-${var.environment}"
network_mode = "awsvpc"
task_role_arn = aws_iam_role.task_role.arn
# Fargate requirements
requires_compatibilities = compact([var.ecs_use_fargate ? "FARGATE" : ""])
cpu = var.ecs_use_fargate ? var.fargate_task_cpu : ""
memory = var.ecs_use_fargate ? var.fargate_task_memory : ""
execution_role_arn = join("", aws_iam_role.task_execution_role.*.arn)
container_definitions = var.container_definitions == "" ? local.default_container_definitions : var.container_definitions
dynamic "volume" {
for_each = var.container_volumes
content {
name = volume.value.name
dynamic "efs_volume_configuration" {
for_each = try([volume.value.efs_volume_configuration], [])
content {
authorization_config {
access_point_id = try(efs_volume_configuration.value.access_point_id, null)
iam = try(efs_volume_configuration.value.iam, "ENABLED")
}
file_system_id = var.efs_instance_id
root_directory = try(efs_volume_configuration.value.root_directory, "/")
transit_encryption = try(efs_volume_configuration.value.transit_encryption, "ENABLED")
transit_encryption_port = try(efs_volume_configuration.value.transit_encryption_port, null)
}
}
}
}
lifecycle {
ignore_changes = [
requires_compatibilities,
cpu,
memory,
execution_role_arn,
container_definitions,
]
}
}
# Create a data source to pull the latest active revision from
data "aws_ecs_task_definition" "main" {
task_definition = aws_ecs_task_definition.main.family
depends_on = [aws_ecs_task_definition.main] # ensures at least one task def exists
}
locals {
ecs_service_launch_type = var.ecs_use_fargate ? "FARGATE" : "EC2"
fargate_platform_version = var.ecs_use_fargate ? var.fargate_platform_version : null
ecs_service_ordered_placement_strategy = {
EC2 = [
{
type = "spread"
field = "attribute:ecs.availability-zone"
},
{
type = "spread"
field = "instanceId"
},
]
FARGATE = []
}
ecs_service_placement_constraints = {
EC2 = [
{
type = "distinctInstance"
},
]
FARGATE = []
}
ecs_service_agg_security_groups = var.manage_ecs_security_group ? compact(concat(tolist([aws_security_group.ecs_sg[0].id]), var.additional_security_group_ids)) : compact(var.additional_security_group_ids)
}
resource "aws_ecs_service" "main" {
name = var.name
cluster = var.ecs_cluster.arn
launch_type = local.ecs_service_launch_type
platform_version = local.fargate_platform_version
enable_execute_command = var.ecs_exec_enable
# Use latest active revision
task_definition = "${aws_ecs_task_definition.main.family}:${max(
aws_ecs_task_definition.main.revision,
data.aws_ecs_task_definition.main.revision,
)}"
desired_count = var.tasks_desired_count
deployment_minimum_healthy_percent = var.tasks_minimum_healthy_percent
deployment_maximum_percent = var.tasks_maximum_percent
dynamic "ordered_placement_strategy" {
for_each = local.ecs_service_ordered_placement_strategy[local.ecs_service_launch_type]
content {
type = ordered_placement_strategy.value.type
field = ordered_placement_strategy.value.field
}
}
dynamic "placement_constraints" {
for_each = local.ecs_service_placement_constraints[local.ecs_service_launch_type]
content {
type = placement_constraints.value.type
}
}
network_configuration {
subnets = var.ecs_subnet_ids
security_groups = local.ecs_service_agg_security_groups
assign_public_ip = var.assign_public_ip
}
dynamic "load_balancer" {
for_each = var.associate_alb || var.associate_nlb ? var.lb_target_groups : []
content {
container_name = local.target_container_name
target_group_arn = load_balancer.value.lb_target_group_arn
container_port = load_balancer.value.container_port
}
}
health_check_grace_period_seconds = var.associate_alb || var.associate_nlb ? var.health_check_grace_period_seconds : null
enable_ecs_managed_tags = var.enable_ecs_managed_tags
deployment_circuit_breaker {
enable = var.ecs_deployment_circuit_breaker.enable
rollback = var.ecs_deployment_circuit_breaker.rollback
}
dynamic "service_registries" {
for_each = var.service_registries
content {
registry_arn = service_registries.value.registry_arn
container_name = service_registries.value.container_name
container_port = service_registries.value.container_port
port = service_registries.value.port
}
}
lifecycle {
ignore_changes = [task_definition]
}
}