the1
the1

Reputation: 47

Terraform - Append a string to an object in a for_each

How do I go about appending the /* to the end of an object using for_each? The goal is to have Terraform to go through the list of resource_arns and add /* to the end. However, I'm currently getting the error, "invalid template interpolation value".

If I have resources = each.value.resource_arns, then Terraform is able to create the resource, but it would just be without /*, which is not desired.

The desired outcome would be to have the resource created as:

+ Action   = [
    + "s3:PutObject",
    + "s3:GetObject",
    + "s3:DeleteObject",
  ]
+ Effect   = "Allow"
+ Resource = "arn:aws:s3:::my-bucket-here/*"

Error

╷
│ Error: Invalid template interpolation value
│ 
│   on account-iam-policy/module/main.tf line 168, in data "aws_iam_policy_document" "this":
│  168:       resources = ["${each.value.resource_arns}/*"]
│     ├────────────────
│     │ each.value.resource_arns is list of string with 1 element
│ 
│ Cannot include the given value in a string template: string required.
╵

terragrunt.hcl

inputs = {
  service_accounts = {
    "aws-s3-bucket" = {
      name          = "my-s3-bucket"
      policy = {
        "s3-rw" = {
          resource_arns = ["arn:aws:s3:::my-bucket-here"] 
          policy_keys = ["aws_s3_rw_policy"]
        }
      }
    }
}

main.tf

data "aws_iam_policy_document" "this" {
  for_each = var.policy
  dynamic "statement" {
    for_each = contains(each.value.policy_keys, "aws_s3_rw_policy") ? ["apply"] : []
    content {
      effect = "Allow"

      actions = [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ]
 
      resources = ["${each.value.resource_arns}/*"]

    }
  }
}

variables.tf

variable "service_accounts" {
  type = map(object({
    name      = string

    policy = map(object({
      resource_arns = list(string)
      policy_keys   = list(string)
    }))

  }))
}

Upvotes: 0

Views: 1959

Answers (1)

Marcin
Marcin

Reputation: 238687

You have to iterate over resource_arns:

resources = [for arn in each.value.resource_arns: "${arn}/*"]

Upvotes: 3

Related Questions