Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

+ 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)
    }))

  }))
}

>Solution :

You have to iterate over resource_arns:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading