Dynamic AWS provider in terraform

Recently I needed to create a backup vault resource in Cape Town region, but only if the region is enabled in the AWS account. Straight approach:

provider "aws" {
   region = "af-south-1"
   alias  = "af-south-1"
}

resource "aws_backup_vault" "af_south_1" {
   provider = aws.af-south-1
   name     = "default"
}

would throw exception if af-south-1 region is not enabled for the account. Terraform has the ability to create a resource only if certain condition is met (via count = meta property), but it cannot conditionally declare providers.

But we can conditionally redirect the provider.

Even though we cannot enable/disable AWS provider declaration, we can conditionally select region where it’s declared:

data "aws_regions" "current" {}
 
locals {
   af_supported = 
         contains(data.aws_region.current.names, "af-south-1")
}
 
provider "aws" {
   region = local.af_supported? "af-south-1" : "us-west-2"
   alias  = "af-south-1"
}

Here, if af-south-1 region is supported – AWS provider will be initialized in this region. Otherwise it will be initialized in us-west-2.
But we don’t want to create any resources in us-west-2, so we just add this condition to the resource declaration:

resource "aws_backup_vault" "af_south_1" {
   count    = local.af_supported? 1 : 0
   provider = aws.af-south-1
   name     = "default"
}

If af-south-1 region is supported – the resource will be created (with the provider in the correct region). Otherwise resource creation will be skipped.

Leave a Reply

Your email address will not be published. Required fields are marked *