Search code examples
terraformterraform-provider-aws

Accessing Terraform ARN's for resource created using a for_each


I am trying to extract the ARN's of resource and passing these to an IAM policy using a string template but having a few issues and wondering if anyone can help or has any ideas

This is the policy template :

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
          "Effect": "Allow",
          "Action": [
              "firehose:PutRecordBatch"
          ],
          "Resource":
            "${values(aws_kinesis_firehose_delivery_stream.open-search)[*].arn}"
        }
    ]
}
POLICY
}

What I get back is

   │ aws_kinesis_firehose_delivery_stream.open-search is object with 2 attributes

Cannot include the given value in a string template: string required.

The output from values(aws_kinesis_firehose_delivery_stream.open-search)[*].arn is

firehose_delivery_arns = [
      + "arn:aws:firehose:eu-west-1:*:deliverystream/stream1",
      + "arn:aws:firehose:eu-west-1:*:deliverystream/stream2",
    ]

Tried a few string functions in terraform but can't seem to get it work the output from the values seems to be in the correct format that the policy requires but doesn't seem to like it for some reason.


Solution

  • Generating JSON by concatenating strings together is a pretty fraught process, so I would recommend writing this instead as a normal Terraform expression producing the data structure you want to encode, and then passing it to jsonencode as a whole so Terraform can be the one to worry about how to serialize it:

      policy = jsonencode({
        Version = "2012-10-17"
        Statement = [
          {
            Effect   = "Allow"
            Action   = ["firehose:PutRecordBatch"]
            Resource = values(aws_kinesis_firehose_delivery_stream.open-search)[*].arn
          },
        ]
      })