Terraform For Loop Return Object is Empty

Viewed 330

I am trying to create an aws_ecs_task_definition with multiple portMappings from an array of objects. When I use a for statement it prints out an empty array of objects instead of adding the values that I expect it to add. Any idea what I am doing wrong?

Additional context:

In my actual setup the aws_ecs_task_definition is in a module and the variables are passed in when the module is called which is why I am using the for loop in the first place.

Simple as Possible Example:

variable "test" { default = [{ container_port = 80 }, { container_port = 3333 }] }

resource "aws_ecs_task_definition" "default" {
  family                = "foo"
  container_definitions = jsonencode([
    {
      name         = "foo"
      image        = "foo"
      portMappings = [
        for item in var.test :
          { container_port = item.container_port }
      ]
    }
  ])
}

Expected (simplified for brevity):

+ resource "aws_ecs_task_definition" "default" {
  + container_definitions    = jsonencode(
        [
          + {
              + portMappings     = [
                  + {
                  +   container_port = 80
                  + },
                  + {
                  +   container_port = 3333
                  + },
                ]
            },
        ]
    )
}

Actual (simplified for brevity):

+ resource "aws_ecs_task_definition" "default" {
  + container_definitions    = jsonencode(
        [
          + {
              + portMappings     = [
                  + {},
                  + {},
                ]
            },
        ]
    )
}
1 Answers

It should be:

          { containerPort = item.container_port }

not

          { container_port = item.container_port }
Related