JDev
JDev

Reputation: 1822

Terraform - How to modify the map object in Terraform?

I have a map of the format:

datasets   = {
  test = {
    access = [
      {
        role = "OWNER"
        group_by_email = "grp-owner"
      },
      {
        role = "READER"
        group_by_email = "grp-reader"
      }
    ]
  }
  test2 = {
    access = [
      {
        role = "OWNER"
        group_by_email = "grp-owner"
      },
      {
        role = "WRITER"
        group_by_email = "grp-writer"
      }
    ]
  }
}

I a looking for a way to update the map(datasets/{dataset_name}/access/group_by_email) to add the domain name:

datasets   = {
  test = {
    access = [
      {
        role = "OWNER"
        group_by_email = "[email protected]"
      },
      {
        role = "READER"
        group_by_email = "[email protected]"
      }
    ]
  }
  test2 = {
    access = [
      {
        role = "OWNER"
        group_by_email = "[email protected]"
      },
      {
        role = "WRITER"
        group_by_email = "[email protected]"
      }
    ]
  }
}

Upvotes: 3

Views: 3072

Answers (1)

Marcin
Marcin

Reputation: 238209

You can do that as follows:


variable "datasets" {
  default   = {
    test = {
      access = [
        {
          role = "OWNER"
          group_by_email = "grp-owner"
        },
        {
          role = "READER"
          group_by_email = "grp-reader"
        }
      ]
    }
    test2 = {
      access = [
        {
          role = "OWNER"
          group_by_email = "grp-owner"
        },
        {
          role = "WRITER"
          group_by_email = "grp-writer"
        }
      ]
    }
  }
}

locals {
  modified = { for k1, v1 in var.datasets:
                k1 => {access = [
                          for access in v1["access"]:  
                           merge(access, {group_by_email = "${access.group_by_email}@test.com"})
                         ]
                      }
             }
}

which results in:

 {
  "test" = {
    "access" = [
      {
        "group_by_email" = "[email protected]"
        "role" = "OWNER"
      },
      {
        "group_by_email" = "[email protected]"
        "role" = "READER"
      },
    ]
  }
  "test2" = {
    "access" = [
      {
        "group_by_email" = "[email protected]"
        "role" = "OWNER"
      },
      {
        "group_by_email" = "[email protected]"
        "role" = "WRITER"
      },
    ]
  }
}

Upvotes: 5

Related Questions