Unable to use conditional statement for Provider attribute

Hello Team,

I have a code snippet like below to create KMS keys across the regions. I used a list map variable for list of projects and their respective regions like below. I am trying to use for each loop over the map and using Provider attribute to create the keys in single block without repeating the code, but I am getting the following error.


locals {
project_region_map = flatten([
for p,x in var.Projects_Regions : [
for r in x : {
project = p
region = r

project_region = {
for item in local.project_region_map : “{item.project}.{item.region}” => item
Projects_Regions = {
“Smartapp” : [“eu-west-1”, “eu-west-2”]
“Portalapp” : [“eu-west-2”]
“boardingapp” : [“eu-west-2”]

resource “aws_kms_key” “keys_ireland” {
for_each = {
for item in local.project_region_map : “{item.project}.{item.region}” => item
Provider = each.value.region == eu-west-2 ? “aws.london” : “aws”

enable_key_rotation = true
key_usage = “ENCRYPT_DECRYPT”
is_enabled = true

tags = merge(
“Name” = “{each.value.project}-{var.ENV}.kms”
“Purpose” = “KMS Key 01”
“SecurityZone” = “X2”


provider “aws” {
region = “eu-west-2”
alias = “london”

assume_role {
role_arn = var.DEPLOY_ROLE

provider “aws” {
version = “4.2.0”
region = “eu-west-1”

assume_role {
role_arn = var.DEPLOY_ROLE

│ Error: Invalid provider configuration reference

│ on kms_regions.tf line 44, in resource “aws_kms_key” “keys_regions”:
│ 44: provider = (each.value.region == “eu-west-2” ? “aws.london” : “aws”)

│ The provider argument requires a provider type name, optionally followed by a period and then a configuration alias.

Is it not possible to write a conditional statement for Provider?


No, provider references are static because they need to be assigned before any evaluation can happen. Since AWS resource regions are only defined by the provider, you will need to assign each provider configuration to the resources you might want, and conditionally create each instance.

This is often done by putting the resource configurations in a module, and passing the provider into each module config, then only creating instances of the module for the region you want enabled.

Sure, understood so I can use modules or create different resources for different regions with list variables. Thanks much for the quick reply. Really appreciate it.

Check out Provider Configuration - Configuration Language | Terraform | HashiCorp Developer (how to use alias for the same provider with different configuration)

Thank you, there is no issue with aliasing but got the relevant details.