Want Multiple Provider and for_each

I often deploy dev and stg accounts at once from a shard account.
The dev provider and stg provider take over authority through the assume role and proceed with execution.

I want to create identical resources for each provider’s account.

However, when using for_each in the resource, an error occurs in the provider declaration syntax.

My code is as below provider = aws[each.key] Is this kind of declaration difficult?

provider "aws" {
  alias = "shared"
 default_tags {
   tags = {
     Terraform   = true
   }
 }
 region = var.region
}

provider "aws" {
  alias = "dev"
  region = var.region
  assume_role {
    role_arn = var.dev_assume_role_arn
  }
}

provider "aws" {
  alias = "stg"
  region = var.region
  assume_role {
    role_arn = var.stg_assume_role_arn
  }
}

locals {
  multi_provider = ["dev", "stg"]
}

resource "random_id" "bucket_id" {
  byte_length = 8
}

resource "aws_s3_bucket" "some_name" {
  for_each = toset(local.multi_provider)
  provider = aws[each.key]
  bucket   = "${var.s3_bucket_name}-${random_id.bucket_id.hex}-${each.key}"
}
1 Like

I have a very similar use case, but with the kubernetes provider where I’m trying to map creation of one namespace to many clusters.

Unfortunately Terraform does not support this sort of dynamic behavior. The provider argument must be in format aws.stg for example and cannot be used anywhere else.

your option would be to wrap this around a module but the problem here is providers within modules don’t support for_each/counts :frowning_face: so we are sort of stuck.

1 Like

This topic was automatically closed 62 days after the last reply. New replies are no longer allowed.