How to deal with nested for_each loops in dependent ressources

Hi there,

I am trying to create two different ressources based on a nested for_each loop with the second ressource / module being dependent on the first one. Here’s an example:

My input is a YAML file that looks something like this

  - team_name: team1
      - workspace_name: ws1
      - workspace_name: ws2
  - team_name: team2
      - workspace_name: ws3
      - workspace_name: ws4
      - workspace_name: ws5

I am decoding this input into a map and creating one resource for each team using for_each. So far so good.

module "team" {
  for_each = {
    for team in local.yaml_data : team.team_name => team

Afterwards I want to use a second module to create the workspaces for each team using the output values from the “team”-module. Obviously, for ws1 & 2, I need the output values of the first iteration (team1) while for the ws3-5, I need to access the values for team2.

How can I achieve something like this?

Thank your for your help!

The key to this is building the complex for_each expression for the module "workspace" block. It’s really quite non-obvious the first time you have to do something like this.

One way to do this is tucked away in the documentation for the flatten function - flatten - Functions - Configuration Language | Terraform | HashiCorp Developer

I like to write mine broadly equivalent to that, but skipping the separate local variable:

module "workspace" {
  for_each = {
    for item in flatten([
      for team in local.yaml_data : [
        for workspace in team.workspaces : {
          workspace = workspace
          team      = team
    : item.workspace.workspace_name => item

  something =[].something
1 Like

Thank you very much! This is exactly what I was looking for!