Providers in a loop for a data source

Is there any way to do this in a loop

locals {
  regions = {
    california = "us-west-1"
    ireland    = "eu-west-1"
    brazil     = "sa-east-1"
  }
}

data "aws_vpc" "this" {
  for_each = local.regions
  provider = aws[each.key]

  default = false
  filter {
    name   = "tag:Name"
    values = ["example"]
  }
}

Provider aliases have to be static, so you’d need to have a different data block for each region.

1 Like

Indeed, unfortunately the AWS provider models region as a whole-provider-configuration setting rather than as a per-resource setting, due in part to how the underlying APIs represent regions, and so there isn’t currently any way to vary the region dynamically on a per-resource basis.

Some other providers are designed to allow specifying a separate region for each resource which makes this easier, but that’s not how the AWS provider is currently built and it’s challenging to make it work that way because regions in AWS are largely a client-side concept, with the SDKs containing mapping rules for constructing suitable endpoint URLs depending on the region. :confounded:

One way you can reduce (but not eliminate) the boilerplate is to factor out all of your per-region objects into a reusable module and then include one module block per region, passing a different provider configuration into each. In that case you at least only need to write out one module block per region, rather than duplicating every single per-region resource and data block.

1 Like