forked from cloudposse/terraform-aws-codebuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.tf
472 lines (398 loc) · 13.5 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
data "aws_caller_identity" "default" {
}
data "aws_region" "default" {
}
resource "aws_s3_bucket" "cache_bucket" {
#bridgecrew:skip=BC_AWS_S3_13:Skipping `Enable S3 Bucket Logging` check until bridgecrew will support dynamic blocks (https://github.com/bridgecrewio/checkov/issues/776).
#bridgecrew:skip=BC_AWS_S3_14:Skipping `Ensure all data stored in the S3 bucket is securely encrypted at rest` check until bridgecrew will support dynamic blocks (https://github.com/bridgecrewio/checkov/issues/776).
#bridgecrew:skip=CKV_AWS_52:Skipping `Ensure S3 bucket has MFA delete enabled` due to issue in terraform (https://github.com/hashicorp/terraform-provider-aws/issues/629).
count = module.this.enabled && local.s3_cache_enabled ? 1 : 0
bucket = local.cache_bucket_name_normalised
acl = "private"
force_destroy = true
tags = module.this.tags
versioning {
enabled = var.versioning_enabled
}
dynamic "logging" {
for_each = var.access_log_bucket_name != "" ? [1] : []
content {
target_bucket = var.access_log_bucket_name
target_prefix = "logs/${module.this.id}/"
}
}
lifecycle_rule {
id = "codebuildcache"
enabled = true
prefix = "/"
tags = module.this.tags
expiration {
days = var.cache_expiration_days
}
}
dynamic "server_side_encryption_configuration" {
for_each = var.encryption_enabled ? ["true"] : []
content {
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
}
}
resource "random_string" "bucket_prefix" {
count = module.this.enabled ? 1 : 0
length = 12
number = false
upper = false
special = false
lower = true
}
locals {
cache_bucket_name = "${module.this.id}${var.cache_bucket_suffix_enabled ? "-${join("", random_string.bucket_prefix.*.result)}" : ""}"
## Clean up the bucket name to use only hyphens, and trim its length to 63 characters.
## As per https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
cache_bucket_name_normalised = substr(
join("-", split("_", lower(local.cache_bucket_name))),
0,
min(length(local.cache_bucket_name), 63),
)
s3_cache_enabled = var.cache_type == "S3"
## This is the magic where a map of a list of maps is generated
## and used to conditionally add the cache bucket option to the
## aws_codebuild_project
cache_options = {
"S3" = {
type = "S3"
location = module.this.enabled && local.s3_cache_enabled ? join("", aws_s3_bucket.cache_bucket.*.bucket) : "none"
},
"LOCAL" = {
type = "LOCAL"
modes = var.local_cache_modes
},
"NO_CACHE" = {
type = "NO_CACHE"
}
}
# Final Map Selected from above
cache = local.cache_options[var.cache_type]
}
resource "aws_iam_role" "default" {
count = module.this.enabled ? 1 : 0
name = module.this.id
assume_role_policy = data.aws_iam_policy_document.role.json
force_detach_policies = true
tags = module.this.tags
}
data "aws_iam_policy_document" "role" {
statement {
sid = ""
actions = [
"sts:AssumeRole",
]
principals {
type = "Service"
identifiers = ["codebuild.amazonaws.com"]
}
effect = "Allow"
}
}
resource "aws_iam_policy" "default" {
count = module.this.enabled ? 1 : 0
name = module.this.id
path = "/service-role/"
policy = data.aws_iam_policy_document.combined_permissions.json
}
resource "aws_iam_policy" "default_cache_bucket" {
count = module.this.enabled && local.s3_cache_enabled ? 1 : 0
name = "${module.this.id}-cache-bucket"
path = "/service-role/"
policy = join("", data.aws_iam_policy_document.permissions_cache_bucket.*.json)
}
data "aws_s3_bucket" "secondary_artifact" {
count = module.this.enabled ? (var.secondary_artifact_location != null ? 1 : 0) : 0
bucket = var.secondary_artifact_location
}
data "aws_iam_policy_document" "permissions" {
count = module.this.enabled ? 1 : 0
statement {
sid = ""
actions = compact(concat([
"codecommit:GitPull",
"ecr:BatchCheckLayerAvailability",
"ecr:CompleteLayerUpload",
"ecr:GetAuthorizationToken",
"ecr:InitiateLayerUpload",
"ecr:PutImage",
"ecr:UploadLayerPart",
"ecs:RunTask",
"iam:PassRole",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"ssm:GetParameters",
"secretsmanager:GetSecretValue",
], var.extra_permissions))
effect = "Allow"
resources = [
"*",
]
}
dynamic "statement" {
for_each = var.secondary_artifact_location != null ? [1] : []
content {
sid = ""
actions = [
"s3:PutObject",
"s3:GetBucketAcl",
"s3:GetBucketLocation"
]
effect = "Allow"
resources = [
join("", data.aws_s3_bucket.secondary_artifact.*.arn),
"${join("", data.aws_s3_bucket.secondary_artifact.*.arn)}/*",
]
}
}
}
data "aws_iam_policy_document" "vpc_permissions" {
count = module.this.enabled && var.vpc_config != {} ? 1 : 0
statement {
sid = ""
actions = [
"ec2:CreateNetworkInterface",
"ec2:DescribeDhcpOptions",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSubnets",
"ec2:DescribeSecurityGroups",
"ec2:DescribeVpcs"
]
resources = [
"*",
]
}
statement {
sid = ""
actions = [
"ec2:CreateNetworkInterfacePermission"
]
resources = [
"arn:aws:ec2:${var.aws_region}:${var.aws_account_id}:network-interface/*"
]
condition {
test = "StringEquals"
variable = "ec2:Subnet"
values = formatlist(
"arn:aws:ec2:${var.aws_region}:${var.aws_account_id}:subnet/%s",
var.vpc_config.subnets
)
}
condition {
test = "StringEquals"
variable = "ec2:AuthorizedService"
values = [
"codebuild.amazonaws.com"
]
}
}
}
data "aws_iam_policy_document" "combined_permissions" {
override_policy_documents = compact([
join("", data.aws_iam_policy_document.permissions.*.json),
var.vpc_config != {} ? join("", data.aws_iam_policy_document.vpc_permissions.*.json) : null
])
}
data "aws_iam_policy_document" "permissions_cache_bucket" {
count = module.this.enabled && local.s3_cache_enabled ? 1 : 0
statement {
sid = ""
actions = [
"s3:*",
]
effect = "Allow"
resources = [
join("", aws_s3_bucket.cache_bucket.*.arn),
"${join("", aws_s3_bucket.cache_bucket.*.arn)}/*",
]
}
}
resource "aws_iam_role_policy_attachment" "default" {
count = module.this.enabled ? 1 : 0
policy_arn = join("", aws_iam_policy.default.*.arn)
role = join("", aws_iam_role.default.*.id)
}
resource "aws_iam_role_policy_attachment" "default_cache_bucket" {
count = module.this.enabled && local.s3_cache_enabled ? 1 : 0
policy_arn = join("", aws_iam_policy.default_cache_bucket.*.arn)
role = join("", aws_iam_role.default.*.id)
}
resource "aws_codebuild_source_credential" "authorization" {
count = module.this.enabled && var.private_repository ? 1 : 0
auth_type = var.source_credential_auth_type
server_type = var.source_credential_server_type
token = var.source_credential_token
user_name = var.source_credential_user_name
}
resource "aws_codebuild_project" "default" {
count = module.this.enabled ? 1 : 0
name = module.this.id
description = var.description
concurrent_build_limit = var.concurrent_build_limit
service_role = join("", aws_iam_role.default.*.arn)
badge_enabled = var.badge_enabled
build_timeout = var.build_timeout
source_version = var.source_version != "" ? var.source_version : null
tags = {
for name, value in module.this.tags :
name => value
if length(value) > 0
}
artifacts {
type = var.artifact_type
location = var.artifact_location
}
# Since the output type is restricted to S3 by the provider (this appears to
# be an bug in AWS, rather than an architectural decision; see this issue for
# discussion: https://github.com/hashicorp/terraform-provider-aws/pull/9652),
# this cannot be a CodePipeline output. Otherwise, _all_ of the artifacts
# would need to be secondary if there were more than one. For reference, see
# https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CodeBuild.html#action-reference-CodeBuild-config.
dynamic "secondary_artifacts" {
for_each = var.secondary_artifact_location != null ? [1] : []
content {
type = "S3"
location = var.secondary_artifact_location
artifact_identifier = var.secondary_artifact_identifier
encryption_disabled = ! var.secondary_artifact_encryption_enabled
# According to AWS documention, in order to have the artifacts written
# to the root of the bucket, the 'namespace_type' should be 'NONE'
# (which is the default), 'name' should be '/', and 'path' should be
# empty. For reference, see https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectArtifacts.html.
# However, I was unable to get this to deploy to the root of the bucket
# unless path was also set to '/'.
path = "/"
name = "/"
}
}
cache {
type = lookup(local.cache, "type", null)
location = lookup(local.cache, "location", null)
modes = lookup(local.cache, "modes", null)
}
environment {
compute_type = var.build_compute_type
image = var.build_image
type = var.build_type
privileged_mode = var.privileged_mode
environment_variable {
name = "AWS_REGION"
value = signum(length(var.aws_region)) == 1 ? var.aws_region : data.aws_region.default.name
}
environment_variable {
name = "AWS_ACCOUNT_ID"
value = signum(length(var.aws_account_id)) == 1 ? var.aws_account_id : data.aws_caller_identity.default.account_id
}
dynamic "environment_variable" {
for_each = signum(length(var.image_repo_name)) == 1 ? [""] : []
content {
name = "IMAGE_REPO_NAME"
value = var.image_repo_name
}
}
dynamic "environment_variable" {
for_each = signum(length(var.image_tag)) == 1 ? [""] : []
content {
name = "IMAGE_TAG"
value = var.image_tag
}
}
dynamic "environment_variable" {
for_each = signum(length(module.this.stage)) == 1 ? [""] : []
content {
name = "STAGE"
value = module.this.stage
}
}
dynamic "environment_variable" {
for_each = signum(length(var.github_token)) == 1 ? [""] : []
content {
name = "GITHUB_TOKEN"
value = var.github_token
type = var.github_token_type
}
}
dynamic "environment_variable" {
for_each = var.environment_variables
content {
name = environment_variable.value.name
value = environment_variable.value.value
type = environment_variable.value.type
}
}
}
source {
buildspec = var.buildspec
type = var.source_type
location = var.source_location
report_build_status = var.report_build_status
git_clone_depth = var.git_clone_depth != null ? var.git_clone_depth : null
dynamic "auth" {
for_each = var.private_repository ? [""] : []
content {
type = "OAUTH"
resource = join("", aws_codebuild_source_credential.authorization.*.id)
}
}
dynamic "git_submodules_config" {
for_each = var.fetch_git_submodules ? [""] : []
content {
fetch_submodules = true
}
}
}
dynamic "secondary_sources" {
for_each = var.secondary_sources
content {
git_clone_depth = secondary_source.value.git_clone_depth
location = secondary_source.value.location
source_identifier = secondary_source.value.source_identifier
type = secondary_source.value.type
insecure_ssl = secondary_source.value.insecure_ssl
report_build_status = secondary_source.value.report_build_status
git_submodules_config {
fetch_submodules = secondary_source.value.fetch_submodules
}
}
}
dynamic "vpc_config" {
for_each = length(var.vpc_config) > 0 ? [""] : []
content {
vpc_id = lookup(var.vpc_config, "vpc_id", null)
subnets = lookup(var.vpc_config, "subnets", null)
security_group_ids = lookup(var.vpc_config, "security_group_ids", null)
}
}
dynamic "logs_config" {
for_each = length(var.logs_config) > 0 ? [""] : []
content {
dynamic "cloudwatch_logs" {
for_each = contains(keys(var.logs_config), "cloudwatch_logs") ? { key = var.logs_config["cloudwatch_logs"] } : {}
content {
status = lookup(cloudwatch_logs.value, "status", null)
group_name = lookup(cloudwatch_logs.value, "group_name", null)
stream_name = lookup(cloudwatch_logs.value, "stream_name", null)
}
}
dynamic "s3_logs" {
for_each = contains(keys(var.logs_config), "s3_logs") ? { key = var.logs_config["s3_logs"] } : {}
content {
status = lookup(s3_logs.value, "status", null)
location = lookup(s3_logs.value, "location", null)
encryption_disabled = lookup(s3_logs.value, "encryption_disabled", null)
}
}
}
}
}