From d8107b86f8381f18ce2779ad56e5bb98803244c0 Mon Sep 17 00:00:00 2001 From: "waqas.yousaf" Date: Wed, 30 Oct 2024 16:22:38 +0100 Subject: [PATCH] OPS-6301: Adjusted to Apply policy to multiple accounts --- main.tf | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/main.tf b/main.tf index dee4464..dc373ff 100644 --- a/main.tf +++ b/main.tf @@ -7,11 +7,30 @@ resource "aws_organizations_policy" "scp" { content = templatefile(lookup(each.value, "file"), {}) } +# Create a local variable to flatten policies with target IDs +locals { + policy_attachments = [ + for policy in var.policies : [ + for target_id in policy.target_ids : { + policy_name = policy.name + target_id = target_id + } + ] + ] +} + +# Flatten the local variable to a single list of attachments +locals { + flattened_policy_attachments = flatten(local.policy_attachments) +} + +# Attach SCP policies to multiple target accounts or OUs resource "aws_organizations_policy_attachment" "attach_scp" { for_each = { - for policy in aws_organizations_policy.scp : - policy.name => policy + for idx, attachment in local.flattened_policy_attachments : + "${attachment.policy_name}-${attachment.target_id}" => attachment } - policy_id = each.value.id - target_id = flatten([for p in var.policies : p.target_ids if p.name == each.key])[0] + + policy_id = aws_organizations_policy.scp[each.value.policy_name].id + target_id = each.value.target_id }