flashbang
flashbang

Reputation: 172

Terraform - conditionally merge multiple aws_iam_policy_document

For starters, I've read this question, but that solution is rather hacky and I'm hoping that with the newer version of Terraform that there's a more elegant way to achieve this.

I have multiple IAM policy documents like this:

data "aws_iam_policy_document" "policy1" { 
  ...
}

data "aws_iam_policy_document" "policy2" { 
  ...
}

data "aws_iam_policy_document" "policy3" { 
  ...
}

And I'm attempting to merge them into one document with source_policy_documents, like so:

data "aws_iam_policy_document" "combined" {
  source_policy_documents = [
    data.aws_iam_policy_document.policy1.json
    data.aws_iam_policy_document.policy2.json
    data.aws_iam_policy_document.policy3.json
  ]
}

I would like to offer "override" variables to allow users to exclude each document from being merged into the final policy.

I'm new to Terraform - is there a straightforward way to either dynamically construct source_policy_documents or maybe use override_policy_documents to get what I want?

Thanks!

Upvotes: 5

Views: 7864

Answers (1)

Technowise
Technowise

Reputation: 1357

This may not be the most efficient, but you could do something like this: I am assuming that you have some boolean variables to indicate the policies to be enabled or disabled (policy1_enable, policy2_enable, policy3_enable).

data "aws_iam_policy_document" "combined" {
  source_policy_documents = concat(
    var.policy1_enable == true? [data.aws_iam_policy_document.policy1.json]:[],
    var.policy2_enable == true? [data.aws_iam_policy_document.policy2.json]:[],
    var.policy3_enable == true? [data.aws_iam_policy_document.policy3.json]:[])
}

Upvotes: 13

Related Questions