Problem
Terraform does not currently support using the count or for_each meta-arguments within a providerconfiguration block. This is a long-requested feature that would allow for the dynamic creation of provider configurations based on input variables.
Cause
This limitation is due to Terraform's evaluation model. Provider configurations must be resolved and configured before Terraform builds the dependency graph of resources. Since count and for_each are evaluated as part of the graph walk, their values are not available early enough in the process to dynamically configure providers.
For more background, you can review these community and developer discussions:
- GitHub Issue #19932: Support for_each/count on provider blocks
- GitHub Issue #25244: Allow use of variables in provider blocks
- GitHub Issue #24476: Allow interpolating module outputs in provider blocks
- HashiCorp Discuss: How to instantiate dynamic providers
- HashiCorp Discuss: Dynamic provider support
Solutions
While you cannot use meta-arguments directly in a provider block, the following workarounds can help you achieve a similar outcome.
Solution 1: Generate Configuration Files with External Tooling
You can use an external scripting language, such as Bash or PowerShell, to programmatically generate the necessary *.tf files. The script can loop through a list of required configurations (e.g., regions or accounts) and create a distinct provider block for each one in a dedicated configuration file.
Solution 2: Use Dynamically Created Workspaces
You can use the tfeprovider to dynamically create workspaces in HCP Terraform or Terraform Enterprise for each distinct provider configuration. Each workspace can then be configured with the necessary environment variables to configure its provider.
For example, to create multiple AWS provider configurations for different regions, the AWS provider can use the AWS_DEFAULT_REGIONenvironment variable to set the working region for each workspace.
Solution 3: Use the Cloud Development Kit for Terraform (CDKTF)
The CDK for Terraform allows you to define infrastructure using a general-purpose programming language like TypeScript, Python, or Go. This approach grants you the flexibility to use native language features, such as for loops, to define dynamic provider configurations that are then synthesized into standard Terraform JSON configuration.