Replace items in config map

Hi community, I am fairly new with terraform, but I would like to manage something (if it is even possible). I would like to manage to pass different environment variables to different lambdas in a configurable way. Let’s say I have this config map:

> local.config
{
  "lambdas" = [
    {
      "name" = "lambda1"
      "envs" = [
           "s2s_username" ,
           "s2s_password",
           "region",
           "project",
      ]
    },
    {
      "name" = "lambda2"
      "envs" = [
        "project",
      ]
    },
  ]
  "project" = "animals"
  "s2s_password" = "cat_tail"
  "s2s_username" = "lion"
}

I would like to somehow manage to have another map I could use with lambda module, which should look like this:

  "lambdas" = [
    {
      "name" = "lambda1"
      "envs" = [
        "s2s_username"="lion" ,
        "s2s_password"="cat_tail",
        "region"="us-east-1",
        "project"="animals",
      ]
    },
    {
      "name" = "lambda2"
      "envs" = [
        "project"="animals",
      ]

I am passing the variables to the module and there I create a local env_vars map:

locals {
    env_vars = {
        s2s_username = var.s2s_username
        s2s_password = var.s2s_password
        region = var.region
        project = var.project
    }

I can not figure out how I should replace/add or flatten my config to be able to create that map in order to create lambdas with specific environment variables.

Hi @andraslorinc!

This “lambdas” value seems to be a list of objects rather than a map, and so it’s harder to achieve your goal which seems to involve correlating elements by their names.

I would suggest first changing these data structures to be a map of objects where the map keys are the function names, because then you can look up a particular object by its name instead of having to search the whole list to find the one matching element.

Your “envs” values seem to be invalid in this example too. I’m assuming you intended them to be maps (using { ... }) but you showed it using square brackets [ ... ]. You will need to fix this before Terraform will accept this expression as valid

Once you have two maps of objects you can write a for expression which merges them together using whatever logic is appropriate for your case. For example, if the goal is to merge together the “envs” maps, preferring the values from the second data structure if there are conflicts, then you could write it this way:

locals {
  merged_lambdas = tomap({
    for k, o in local.lambdas_1 : k => {
      envs = tomap(merge(
        o.envs,
        try(local.lambdas_2[k].envs, {}),
      ))
    }
  })
}

Here I’ve used local.lambdas_1 to represent the main map from name to object, and local.lambdas_2 to represent the second map you wanted to merge from.

The result will be another map of objects with the same keys as the first map but with the envs maps merged with the ones from the second map.