ducleaux
ducleaux

Reputation: 53

Is there a way to iterate over provider?

I have setted up two providers (2 aws accounts), I want to launch an ec2 instance on each of the accounts without having to repeat code.

I tried using loops with count and for_each but no luck.

variable "providers" {
  default = [
    "aws.dev",
    "aws.qa"
  ]
}

resource "aws_instance" "test" {
  for_each      = toset(var.providers)
  ami           = "ami-0dc9a8d2479a3c7d7"
  instance_type = "t2.micro"
  provider      = each.value
}

I got the next error:

Error: provider.each: no suitable version installed version requirements: "(any version)" versions installed: none

I tried similar code iterating over other values like ami's, instance types and it works.

I'm not sure if there's something I'm not seeing or iteration over providers it's not supported.

Any idea or workaround for this? Thanks.

Upvotes: 4

Views: 4584

Answers (1)

Martin Atkins
Martin Atkins

Reputation: 74564

Terraform associates resources with providers prior to other processing (because the provider selection affects the meaning of aws_instance and thus what else is valid inside), so the provider argument must be a literal reference to a provider. The error message here is because Terraform thinks that you are requesting a provider configuration for a provider called "each" and alias = "value", and so it's trying to install that provider.

The main way to represent multiple environments in Terraform is to use a separate root module for each environment, containing the backend and provider configurations for that environment, and then factor out the common elements shared between environments into one or more shared modules. You can then apply changes to each environment separately, reducing the risk that making a chance to one environment will inadvertently affect another.

Upvotes: 1

Related Questions