Skip to content

Commit af5bf61

Browse files
committed
conditionally create policy for writing to S3 bucket
1 parent 15650cd commit af5bf61

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

main.tf

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,36 @@
11
locals {
2+
log_prefix_computed = (
3+
var.log_prefix != null
4+
? replace("/${var.log_prefix}/*", "//{2,}/", "/")
5+
: "/*"
6+
)
7+
}
8+
9+
data "aws_iam_policy_document" "log_write" {
10+
count = var.log_bucket != null ? 1 : 0
11+
12+
statement {
13+
actions = ["s3:PutObject"]
14+
resources = ["arn:aws:s3:::${var.log_bucket}${local.log_prefix_computed}"]
15+
}
16+
}
17+
18+
resource "aws_iam_policy" "log_write" {
19+
count = var.log_bucket != null ? 1 : 0
20+
21+
description = "IAM policy granting write access to the logging bucket for ${var.name}"
22+
name_prefix = "${var.name}-logging-policy-"
23+
policy = data.aws_iam_policy_document.log_write[count.index].json
24+
}
25+
26+
locals {
27+
core_iam_policies = [
28+
"arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
29+
"arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder"
30+
]
231
iam_policies = concat(
3-
[
4-
"arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
5-
"arn:aws:iam::312594956781:policy/ec2-image-builder-logging",
6-
"arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder",
7-
],
32+
local.core_iam_policies,
33+
aws_iam_policy.log_write[*].arn,
834
var.additional_iam_policy_arns
935
)
1036
}
@@ -33,7 +59,11 @@ resource "aws_iam_role" "this" {
3359
}
3460

3561
resource "aws_iam_role_policy_attachment" "this" {
36-
count = length(local.iam_policies)
62+
count = (
63+
var.log_bucket == null
64+
? length(local.core_iam_policies) + length(var.additional_iam_policy_arns)
65+
: length(local.core_iam_policies) + length(var.additional_iam_policy_arns) + 1
66+
)
3767

3868
policy_arn = local.iam_policies[count.index]
3969
role = aws_iam_role.this.name

0 commit comments

Comments
 (0)