forked from trussworks/terraform-aws-ecs-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.tf
495 lines (410 loc) · 14.6 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
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}"
merged_tags = merge(
var.tags,
var.cost_tags)
# 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,
)
)
}
#
# 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
tags = local.merged_tags
}
resource "aws_cloudwatch_metric_alarm" "alarm_cpu" {
count = var.cloudwatch_alarm_cpu_enable && (var.associate_alb || var.associate_nlb) ? 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
tags = local.merged_tags
dimensions = {
"ClusterName" = var.ecs_cluster.name
"ServiceName" = aws_ecs_service.main.name
}
}
resource "aws_cloudwatch_metric_alarm" "alarm_mem" {
count = var.cloudwatch_alarm_cpu_enable && (var.associate_alb || var.associate_nlb) ? 1 : 0
alarm_name = "${local.cloudwatch_alarm_name}-mem"
alarm_description = "Monitors ECS CPU 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
tags = local.merged_tags
dimensions = {
"ClusterName" = var.ecs_cluster.name
"ServiceName" = aws_ecs_service.main.name
}
}
resource "aws_cloudwatch_metric_alarm" "alarm_cpu_no_lb" {
count = var.cloudwatch_alarm_cpu_enable && ! (var.associate_alb || var.associate_nlb) ? 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
tags = local.merged_tags
dimensions = {
"ClusterName" = var.ecs_cluster.name
"ServiceName" = aws_ecs_service.main.name
}
}
resource "aws_cloudwatch_metric_alarm" "alarm_mem_no_lb" {
count = var.cloudwatch_alarm_cpu_enable && ! (var.associate_alb || var.associate_nlb) ? 1 : 0
alarm_name = "${local.cloudwatch_alarm_name}-mem"
alarm_description = "Monitors ECS CPU 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
tags = local.merged_tags
dimensions = {
"ClusterName" = var.ecs_cluster.name
"ServiceName" = aws_ecs_service.main.name
}
}
#
# SG - ECS
#
resource "aws_security_group" "ecs_sg" {
name = "ecs-${var.name}-${var.environment}"
description = "${var.name}-${var.environment} container security group"
vpc_id = var.ecs_vpc_id
tags = local.merged_tags
}
resource "aws_security_group_rule" "app_ecs_allow_outbound" {
description = "All outbound"
security_group_id = aws_security_group.ecs_sg.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.associate_alb ? length(local.lb_ingress_container_ports) : 0
description = "Allow in ALB"
security_group_id = aws_security_group.ecs_sg.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.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.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.associate_nlb ? length(local.lb_ingress_container_ports) : 0
description = "Allow in NLB"
security_group_id = aws_security_group.ecs_sg.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.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.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" {
count = var.ecs_use_fargate ? 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" {
count = var.ecs_use_fargate ? 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
#
data "aws_region" "current" {
}
module "ecs_task_definition_main" {
source = "github.com/unifio/terraform-aws-ecs-task-definition"
requires_compatibilities = compact([var.ecs_use_fargate ? "FARGATE" : ""])
cpu = var.ecs_use_fargate ? var.fargate_task_cpu : 0
memory = var.ecs_use_fargate ? var.fargate_task_memory : ""
execution_role_arn = join("", aws_iam_role.task_execution_role.*.arn)
task_role_arn = aws_iam_role.task_role.arn
ipc_mode = var.ecs_use_fargate ? null : var.ipc_mode
pid_mode = var.ecs_use_fargate ? null : var.pid_mode
cpu_container = var.fargate_task_cpu
family = var.family
image = var.container_image
name = "${var.name}-${var.environment}"
memory_container = var.fargate_task_memory
mountPoints = var.mountPoints
portMappings = var.portMappings
placement_constraints = var.placement_constraints
volumes = var.volumes
tags = var.tags
cost_tags = var.cost_tags
command = var.command
network_mode = "awsvpc"
volumesFrom = var.volumesFrom
user = var.user
ulimits = var.ulimits
systemControls = var.systemControls
secrets = var.secrets
resourceRequirements = var.resourceRequirements
repositoryCredentials = var.repositoryCredentials
register_task_definition = var.register_task_definition
readonlyRootFilesystem = var.readonlyRootFilesystem
pseudoTerminal = var.pseudoTerminal
memoryReservation = var.memoryReservation
linuxParameters = var.linuxParameters
links = var.links
interactive = var.interactive
hostname = var.hostname
healthCheck = var.healthCheck
extraHosts = var.extraHosts
entryPoint = var.entryPoint
dockerSecurityOptions = var.dockerSecurityOptions
dockerLabels = var.dockerLabels
dnsServers = var.dnsServers
dnsSearchDomains = var.dnsSearchDomains
disableNetworking = var.disableNetworking
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = local.awslogs_group,
awslogs-region = data.aws_region.current.name,
awslogs-stream-prefix = "${var.name}-ecs"
}
}
workingDirectory = var.workingDirectory
}
# Create a data source to pull the latest active revision from
data "aws_ecs_task_definition" "main" {
task_definition = module.ecs_task_definition_main.family
depends_on = [module.ecs_task_definition_main] # ensures at least one task def exists
}
locals {
ecs_service_launch_type = var.ecs_use_fargate ? "FARGATE" : "EC2"
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 = compact(concat(list(aws_security_group.ecs_sg.id), 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
tags = local.merged_tags
# Use latest active revision
task_definition = "${module.ecs_task_definition_main.family}:${max(
module.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.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
}
}
lifecycle {
ignore_changes = [task_definition]
}
}