Skip to content

Instantiating Multiple Providers with a loop #19932

@JakeNeyer

Description

@JakeNeyer

Current Terraform Version

Terraform v0.11.11

Use-cases

In my current situation, I am using the AWS provider so I will scope this feature request to that specific provider, although this may extend to other providers as well.

I am attempting to create resources in multiple AWS accounts. The number of the accounts ranges from 0....x and will be dynamic. I would like to be able to instantiate multiple providers which can assume a role in each account, and in turn, create resources with the associated provider without hard-coding providers for each subsequent account.

For example, something like this:

variable "accounts" {
  type    = "list"

  default = ["123456789012", "210987654321"]
}
variable "names" {
  type = "map"

  default = {
    "123456789012" = "foo"
    "210987654321" = "bar"
  }
}
provider "aws" {
  count   = "${length(var.accounts)}"
  alias   = "${lookup(var.names, element(var.accounts, count.index))}"
  
  assume_role {
    role_arn = "arn:aws:iam::${element(var.accounts, count.index)}:role/ASSUMEDROLE"
  }

resource "aws_instance" "web" {
  count         = "${length(var.accounts)}"
  provider      = "aws.${lookup(var.names, element(var.accounts, count.index))}"
  ami           = "${data.aws_ami.ubuntu.id}"
  instance_type = "t2.micro"

  tags = {
    Name = "HelloWorld"
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions