Dynamic block using object with object

I am trying to set up this terraform using Terraform workspaces. I’m building a lambda function that has different environment variables for each environment. I cannot figure out how to use the variable format I am using and then populating them. When I try to

var.tf:

variable "env_vars" {
  default = {
    dev = {
      foo = "manshoo"
      poo = "doo"
    },
    staging = {
      purple = "blue"
      orange = "red"
    },
    prod = {
      triangle = "square"
      rectangle = "circle"
    }
  }
}

If I try this; it seems to want to use all the environments and fails with No more than 1 "environment" blocks are allowed :
main.tf:

resource "aws_lambda_function" "function" {
...
...
...
  dynamic "environment" {
    for_each = var.env_vars

    content {
      variables = environment.value
    }
  }
}

If I do this; it picks up the environment but now instead of seeing the object it’s seeing the objects inside the object

main.tf

resource "aws_lambda_function" "function" {
...
...
  dynamic "environment" {
    for_each = var.env_vars[terraform.workspace]

    content {
      variables = environment.value
    }
  }
}

How do I get the dynamic block to read the environment and populated variable with the nested object?

The only way I can seem to get it to work is to finagle the variable and make it a bit ugly. I can’t seem to find a more elegant method.

vars.tf:

variable "env_vars" {
  default = {
    dev = {
      vars = {
        orange = "yellow"
        red = "blue"
      }
    },
    staging = {
      vars = {
        circle = "square"
        rectangle = "triangle"
      }
    },
    prod = {
      vars = {
        grape = "kiwi"
        banana = "apple"
      }
    }
  }
}

Hi @wblakecannon,

I think your intention here is to treat the keys of var.env_vars as workspace names, and therefore to select just one sub-map from it based on terraform.workspace.

If that’s true, then I don’t think you need a dynamic block at all, because you always need only one environment block; dynamic blocks are for when the number of blocks of that type need to vary based on the value of an expression.

variable "env_vars" {
  type = map(map(string))
}

resource "aws_lambda_function" "example" {
  # ...

  environment {
    variables = var.env_vars[terraform.workspace]
  }
}