4

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.

ducleaux
  • 53
  • 1
  • 3

1 Answers1

1

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.

Martin Atkins
  • 62,420
  • 8
  • 120
  • 138
  • Thanks for your explanation. Separating root module for each environment means that "terraform apply" will need to run each time per environment as well right? – ducleaux Oct 29 '19 at 08:23
  • Yes, `terraform apply` will apply changes to only one configuration at a time. For many users, that's an advantage because it means that they can e.g. apply changes to a staging environment without any risk of affecting a production environment, can easily keep their credentials for each environment entirely separated from each other, etc. – Martin Atkins Oct 29 '19 at 17:05
  • 1
    And for many cases is also a HUGE disadvantage, like for example if you are doing peerings to multiple AWS accounts, you are not going to have 10 different applies for this. – Ulukai Nov 13 '20 at 10:54