Invalid AWS region error

I am attempting to pick a random region when deploying my AWS resources.

From the Terraform console I’ve been able to confirm my syntax related to the random_shuffle resource and element is correct and will return a single string but Terraform continues to say Error: Invalid AWS Region:

Is the problem coming from me wanting to use a value known only after the apply? If so is there another good way of achieving my intended result? I am deploying Lightsail instances so using the data resource of available zone would not suffice here due to it being tied specifically to EC2.

locals {
  region = element(random_shuffle.regions.result, 0)
}

resource "random_shuffle" "regions" {
  input = ["us-east-1", "us-east-2", "us-west-2", "ca-central-1",
  "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-north-1"]
  result_count = 1
}

provider "aws" {
  region     = local.region
  access_key = var.AWS_ACCESS_KEY
  secret_key = var.AWS_SECRET_KEY
}

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "5.38.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "3.6.0"
    }
  }
}

I was able to get a multistep solution working by using target to apply the region value to the state first then run a normal apply to finish the remaining resources.

terraform apply -target=random_shuffle.regions
terraform apply

Hi @castironclay,

The random_shuffle resource type generates its result only during the apply step, and so this configuration would cause the region to be unknown during planning.

The AWS provider cannot configure itself when the region is unknown. The error message is confusing because it’s reporting that the region is an empty string rather than an unknown value, but I happen to know that this is how the AWS provider interprets unknown values in that location.

Unfortunately I don’t think there’s any better alternative here than the two-step apply with -target that you already found. That asks Terraform to generate the random result first, so that the region has already been chosen by the time you perform the second plan/apply round.

1 Like

Excellent. Thanks @apparentlymart