`for_each` and `providers` within module blocks

Hello,

I’m wondering if there is any way to get for_each and providers to work together within a module block.

At the moment I have to do this:

module "foo_blue" {
  ...
  providers = {
    kubernetes = kubernetes.blue
  }
}

module "foo_green" {
  ...
  providers = {
    kubernetes = kubernetes.green
  }
}

What I would like to do is something like this:

module "foo" {
  ...
  for_each = { 
    blue = {}
    green = {}
  }
  providers = {
    kubernetes = "kubernetes.${each.key}"
  }
}

The above doesn’t work due to the providers input value being invalid.
Is it possible to get any form of dynamic value selection into the providers map?

When provisioning and configuring multiple kubernetes clusters within a single Terraform root module, I often have a hard time dealing with providers.
If users were allowed to put logic (eg. functions or if/else) in the provider definition, this would be a lot easier.

Hi @djfinnoy,

There is no way to dynamically assign provider configurations to resources. Terraform connects resources with provider configurations statically as part of building the dependency graph, before evaluating any expressions, and unfortunately that therefore also applies to providers passed into modules because ultimately that’s just an indirection over assigning provider configurations to the individual resources inside the module.

In this case I would suggest sticking with the two separate module blocks as you showed in your initial example. If your two module calls have some values in common then you could factor them out into local values and refer to them from both blocks, so that the values themselves will still be defined in only one place.

I understand. Thank you for the quick response.