Murakami
Murakami

Reputation: 3770

Nested loops in Terraform

I need to have nested loop logic. F.ex.

I have one local:

locals {
  build_args = {
    api: {
      RAILS_ENV: "production"
    }
    client: {
      NODE_ENV: "production"
    }
  }
}

Now I would like to connect to CircleCI with terraform and set these environments in adequate circleCI projects (api and client). The knowledge about circleci projects (name of a project) I keep here:

apps: {
  api: {
    desired_count: 1,
    load_balancer: {
      container_name: "api",
      container_port: 5000,
      health_check_path: "/",
      listener: {
        path: "api",
      },
    },
    circleci_project: "some-api",
  },
  client: {
    desired_count: 1,
    load_balancer: {
      container_name: "client",
      container_port: 3000,
      health_check_path: "/",
      listener: {
        path: "web",
      },
    },
    circleci_project: "some-client",
  }
}

Now, I need to create resource:

resource "circleci_environment_variable" "this" {
  project = projects_from_apps_var

  name = names_from_local_build_args
  value = value_from_local_build_args
}

So as you can see I need two loops one in another to generate many name/values env pairs for many projects.

Upvotes: 0

Views: 2358

Answers (1)

mariux
mariux

Reputation: 3137

Just create a map keyed by project and variable name and apply a bunch of resources for each combination:

locals {
  map = merge([
    for project, env in local.build_args : {
      for name, value in env : "${project}-${name}" => {
        name    = name,
        value   = value,
        project = project
      }
    }
  ]...)
}

resource "circleci_environment_variable" "this" {
  for_each = local.map

  project = each.value.project
  name    = each.value.name
  value   = each.value.value
}

Upvotes: 4

Related Questions