terraformterragrunthashicorpterraform-enterpriseterraformer

Terraform: Nested for expression with no duplicity


I am newbie to Terraform, apologies in advance in case inappropriate logic is used.

There is nested map, want to create new map using existing one.

terraform.tfvars

vpcs_info= {
  "devops" = {
    main = {
      cidr = "10.14.0.0/16"
      region = "ap-south-1"
      peering = {
        creator = {
          devops = "poc",
          uat    = "main"
        }
      }
    },
    poc = {
      cidr = "10.9.0.0/16"
      region = "ap-south-1"
      peering = {
        creator = {
          dev = "main"
        }
      }
    }
  }
}

locas.tf

locals {
  vpcs_info = {
    for vpc, properties in var.vpcs_info.devops:
      vpc => {for dst_env, dst_vpc in properties.peering.creator : vpc => {"name": "${dst_env}-${dst_vpc}-vpc", "id": "${timestamp()}" }...}
   }
}

Actual output:

{
  "main" = {
    "main" = [
      {
        "id" = "2023-02-05T21:23:24Z"
        "name" = "devops-poc-vpc"
      },
      {
        "id" = "2023-02-05T21:23:24Z"
        "name" = "uat-main-vpc"
      },
    ]
  }
  "poc" = {
    "poc" = [
      {
        "id" = "2023-02-05T21:23:24Z"
        "name" = "dev-main-vpc"
      },
    ]
  }
}

If we observe, in the output there is duplicity in KEYS. Need to get below desired output using for expression:

Desired output:

{
  "main" = {
      {
        "id" = "2023-02-05T21:23:24Z"
        "name" = "devops-poc-vpc"
      },
      {
        "id" = "2023-02-05T21:23:24Z"
        "name" = "uat-main-vpc"
      }
  }
  "poc" = {
      {
        "id" = "2023-02-05T21:23:24Z"
        "name" = "dev-main-vpc"
      }
  }
}

Note: "id" is sensitive information in actual requirement, to avoid security challenges, "${timestamp()}" is being used here.


Solution

  • You can do that with merge:

      vpcs_info = merge([
        for vpc, properties in var.vpcs_info.devops: {
           for dst_env, dst_vpc in properties.peering.creator: 
              vpc => {
                "name" = "${dst_env}-${dst_vpc}-vpc"
                "id" = "${timestamp()}" 
               }...
           }
       ]...)