Declare multiple providers for a list of regions

Viewed 223

I have a Terraform module that manages AWS GuardDuty.

In the module, an aws_guardduty_detector resource is declared. The resource allows no specification of region, although I need to configure one of these resources for each region in a list. The region used needs to be declared by the provider, apparently(?).

Lack of module for_each seems to be part of the problem, or, at least, module for_each, if it existed, might let me declare the whole module, once for each region.

Thus, I wonder, is it possible to somehow declare a provider, for each region in a list?

Or, short of writing a shell script wrapper, or doing code generation, is there any other clean way to solve this problem that I might not have thought of?

1 Answers

To support similar processes I have found two approaches to this problem

  1. Declare multiple AWS providers in the Terraform module.
  2. Write the module to use a single provider, and then have a separate .tfvars file for each region you want to execute against.

For the first option, it can get messy having multiple AWS providers in one file. You must give each an alias and then each time you create a resource you must set the provider property on the resource so that Terraform knows which region provider to execute against. Also, if the provider for one of the regions can not initialize, maybe the region is down, then the entire script will not run, until you remove it or the region is back up.

For the second option, you can write the Terraform for what resources you need to set up and then just run the module multiple times, once for each regional .tfvars file.

  • prod-us-east-1.tfvars
  • prod-us-west-1.tfvars
  • prod-eu-west-2.tfvars

My preference is to use the second option as the module is simpler and less duplication. The only duplication is in the .tfvars files and should be more manageable.

EDIT: Added some sample .tfvars

prod-us-east-1.tfvars:

region = "us-east-1"
account_id = "0000000000"
tags = {
    env = "prod"
}
dynamodb_read_capacity = 100
dynamodb_write_capacity = 50

prod-us-west-1.tfvars:

region = "us-west-1"
account_id = "0000000000"
tags = {
    env = "prod"
}
dynamodb_read_capacity = 100
dynamodb_write_capacity = 50

We put whatever variables might need to be changed for the service or feature based on environment and/or region. For instance in a testing environment, the dynamodb capacity may be lower than in the production environment.

Related