-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecs.tf
358 lines (322 loc) · 10.2 KB
/
ecs.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
# ----------------------------
# ECS Cluster
# ----------------------------
resource "aws_ecs_cluster" "main" {
name = "${var.project}-cluster"
tags = var.common_tags
}
# ----------------------------
# Locals
# ----------------------------
locals {
aws_account_id = data.aws_caller_identity.current.account_id
service_namespace_id = aws_service_discovery_private_dns_namespace.app.id
}
# ----------------------------
# IAM Policies and Roles
# ----------------------------
## Task Execution Role Policy
resource "aws_iam_policy" "task_execution_role_policy" {
name = "${var.project}-task-exec-role-policy"
path = "/"
description = "Allow retrieving images and adding to logs"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"logs:CreateLogStream",
"logs:CreateLogGroup",
"logs:PutLogEvents"
]
Resource = "*"
},
{
Effect = "Allow"
Action = [
"ssm:GetParameters",
"secretsmanager:GetSecretValue",
"kms:Decrypt"
]
Resource = "*"
}
]
})
}
## Task Execution Role
resource "aws_iam_role" "task_execution_role" {
name = "${var.project}-task-exec-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Principal = {
Service = ["ecs.amazonaws.com", "ecs-tasks.amazonaws.com"]
}
Effect = "Allow"
}
]
})
}
## Attach Task Execution Policy to Role
resource "aws_iam_role_policy_attachment" "task_execution_role_attachment" {
role = aws_iam_role.task_execution_role.name
policy_arn = aws_iam_policy.task_execution_role_policy.arn
}
## App IAM Role
resource "aws_iam_role" "app_iam_role" {
name = "${var.project}-api-task"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Principal = {
Service = ["ecs.amazonaws.com", "ecs-tasks.amazonaws.com"]
}
Effect = "Allow"
}
]
})
tags = var.common_tags
}
## S3 Access Policy
resource "aws_iam_policy" "ecs_s3_access" {
name = "${var.project}-AppS3AccessPolicy"
path = "/"
description = "Allow access to the traffic app S3 bucket"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:PutObject",
"s3:GetObjectAcl",
"s3:GetObject",
"s3:ListBucket",
"s3:DeleteObject",
"s3:PutObjectAcl"
]
Resource = [
"${aws_s3_bucket.app_public_files.arn}/*",
"${aws_s3_bucket.app_public_files.arn}"
]
}
]
})
}
## Attach S3 Access Policy to App IAM Role
resource "aws_iam_role_policy_attachment" "ecs_s3_access_attachment" {
role = aws_iam_role.app_iam_role.name
policy_arn = aws_iam_policy.ecs_s3_access.arn
}
# ----------------------------
# CloudWatch Log Group
# ----------------------------
resource "aws_cloudwatch_log_group" "ecs_task_logs" {
name = "${var.project}-api"
tags = var.common_tags
}
# ----------------------------
# ECS Task Definition
# ----------------------------
resource "aws_ecs_task_definition" "api" {
family = "${var.project}-api"
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = var.cpu
memory = var.memory
execution_role_arn = aws_iam_role.task_execution_role.arn
task_role_arn = aws_iam_role.app_iam_role.arn
container_definitions = jsonencode([
{
name = var.project
image = var.ecr_image_api
essential = true
memoryReservation = 256
environment = flatten([
[
{ name = "DB_HOST", value = aws_db_instance.main.address },
{ name = "DB_NAME", value = aws_db_instance.main.db_name },
{ name = "S3_STORAGE_BUCKET_NAME", value = aws_s3_bucket.app_public_files.bucket },
{ name = "S3_STORAGE_BUCKET_REGION", value = var.region },
{ name = "CSRF_TRUSTED_ORIGINS", value = "https://${aws_route53_record.app.fqdn},http://${aws_route53_record.app.fqdn}" },
{ name = "ALLOWED_HOSTS", value = "${aws_route53_record.app.fqdn},${aws_lb.api.dns_name}" },
{ name = "SERVICE_DISCOVERY_NAMESPACE_ID", value = local.service_namespace_id },
{ name = "SYSTEM_ENV", value = "PRODUCTION" },
{ name = "DEBUG", value = "0" },
{ name = "S3_STORAGE_BACKEND", value = "1" }
],
[for key, value in var.container_env_vars["api"] : { name = key, value = value }]
])
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = aws_cloudwatch_log_group.ecs_task_logs.name
"awslogs-region" = var.region
"awslogs-stream-prefix" = "${var.project}"
}
}
portMappings = [
{
containerPort = 9000
hostPort = 9000
protocol = "tcp"
}
]
},
{
name = "proxy"
image = var.ecr_image_proxy
essential = true
memoryReservation = 256
environment = flatten([
[
{ name = "APP_HOST", value = "127.0.0.1" },
{ name = "APP_PORT", value = "9000" },
{ name = "LISTEN_PORT", value = "8000" },
{ name = "S3_STORAGE_BUCKET_NAME", value = aws_s3_bucket.app_public_files.bucket },
{ name = "S3_STORAGE_BUCKET_REGION", value = var.region }
],
[for key, value in var.container_env_vars["proxy"] : { name = key, value = value }]
])
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = aws_cloudwatch_log_group.ecs_task_logs.name
"awslogs-region" = var.region
"awslogs-stream-prefix" = "proxy"
}
}
portMappings = [
{
containerPort = 8000
hostPort = 8000
protocol = "tcp"
}
]
},
{
name = "init"
image = var.ecr_image_api
essential = false
memoryReservation = 128
command = [
"sh", "-c",
"python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && python manage.py createsu"
]
environment = flatten([
[
{ name = "DB_HOST", value = aws_db_instance.main.address },
{ name = "DB_NAME", value = aws_db_instance.main.db_name },
{ name = "S3_STORAGE_BUCKET_NAME", value = aws_s3_bucket.app_public_files.bucket },
{ name = "S3_STORAGE_BUCKET_REGION", value = var.region },
{ name = "CSRF_TRUSTED_ORIGINS", value = "https://${aws_route53_record.app.fqdn},http://${aws_route53_record.app.fqdn}" },
{ name = "ALLOWED_HOSTS", value = "${aws_route53_record.app.fqdn},${aws_lb.api.dns_name}" },
{ name = "SERVICE_DISCOVERY_NAMESPACE_ID", value = local.service_namespace_id },
{ name = "SYSTEM_ENV", value = "PRODUCTION" },
{ name = "DEBUG", value = "0" },
{ name = "S3_STORAGE_BACKEND", value = "1" }
],
[for key, value in var.container_env_vars["init"] : { name = key, value = value }]
])
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = aws_cloudwatch_log_group.ecs_task_logs.name
"awslogs-region" = var.region
"awslogs-stream-prefix" = "init"
}
}
}
])
tags = var.common_tags
}
# ----------------------------
# Security Group for ECS Service
# ----------------------------
#trivy:ignore:AVD-AWS-0104
resource "aws_security_group" "ecs_service" {
description = "Access for the ECS service"
name = "${var.project}-ecs-service"
vpc_id = module.vpc.vpc_id
egress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 5432
to_port = 5432
protocol = "tcp"
cidr_blocks = module.vpc.private_subnets_cidr_blocks
}
tags = var.common_tags
}
resource "aws_security_group_rule" "allow_alb_health_checks" {
type = "ingress"
from_port = 8000
to_port = 9000
protocol = "tcp"
security_group_id = aws_security_group.ecs_service.id
source_security_group_id = aws_security_group.lb.id
}
# ----------------------------
# ECS Service
# ----------------------------
resource "aws_ecs_service" "api" {
name = "${var.project}-api"
cluster = aws_ecs_cluster.main.name
task_definition = aws_ecs_task_definition.api.arn
desired_count = 1
launch_type = "FARGATE"
force_new_deployment = var.force_new_deployment
network_configuration {
subnets = module.vpc.private_subnets
security_groups = [aws_security_group.ecs_service.id]
assign_public_ip = false
}
deployment_circuit_breaker {
enable = var.enable_deployment_circuit_breaker
rollback = var.enable_rollback
}
load_balancer {
target_group_arn = aws_lb_target_group.api.arn
container_name = "proxy"
container_port = 8000
}
enable_execute_command = var.enable_execute_command
health_check_grace_period_seconds = 120 # 2 minutes
depends_on = [aws_lb_listener.api_https]
tags = var.common_tags
}
# ----------------------------
# Service Discovery
# ----------------------------
resource "aws_service_discovery_service" "app_service" {
name = var.project
dns_config {
namespace_id = local.service_namespace_id
dns_records {
ttl = 10
type = "A"
}
dns_records {
ttl = 10
type = "SRV"
}
routing_policy = "MULTIVALUE"
}
health_check_custom_config {
failure_threshold = 1
}
tags = var.common_tags
}