Home > Back-end >  Terraform: how to create a map from a list of object?
Terraform: how to create a map from a list of object?

Time:03-05

I am new to Terraform.

I have two list of objects and I would like to merge them as a map in terraform:

locals {

  d_streams = [for idx, item in module.website_s3_bucket : {
     format("%s-%s", "s3-audit", item.name) = {
         a = "b"
         c = item.name
     }
     }
  ]

  dev_d_streams = [for idx, item in module.website_s3_bucket : {
     format("%s-%s", "s3-audit-dev", item.name) = {
         g = "b"
         f = item.name
     }
     }
  ]

  // it will be used somewhere in the module later
  test = merge(local.d_streams, local.d_streams)


}

module "website_s3_bucket" {
  for_each = toset(["c1", "c2"])
  source = "./modules/aws-s3-static-website-bucket"

  bucket_name = "robin-test-dec-17-2019"

  mytest = local.test

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

When I run terraform console, I got the following error:

    | local.d_streams is tuple with 2 elements

Call to function "merge" failed: arguments must be maps or objects, got
"tuple".

I understand that d_streams and dev_d_streams are list and it is not possible to merge them together as a map.

How can I loop thru d_streams and dev_d_streams so that it can form a map?

CodePudding user response:

Your syntax creates list of maps, not maps. The correct way to create the maps is:

  d_streams = {for idx, item in  module.website_s3_bucket  : 
     format("%s-%s", "s3-audit", item.name) => {
         a = "b"
         c = item.name
     }
  }

  dev_d_streams = {for idx, item in  module.website_s3_bucket  : 
     format("%s-%s", "s3-audit-dev", item.name) => {
         g = "b"
         f = item.name
     }
   }
  • Related