Derived value in condition

I wish I could use:

data "aws_regions" "all" {
  all_regions = true
  filter {
    name   = "opt-in-status"
    values = ["opted-in", "opt-in-not-required"]
  }
}

variable "region" {
  default     = "us-west-2"
  description = "AWS Region"
  type        = string
  validation {
    condition     = contains(data.aws_regions.all.names, var.region)
    error_message = "You can't deploy in region ${var.region}."
  }
}

Instead I copy-pasta some CLI output, which at least I can document in the configuration:

variable "region" {
  default     = "us-west-2"
  description = "AWS Region"
  type        = string
  validation {
    condition = contains(
      # aws ec2 describe-regions --all-regions --output json \
      # --filter Name="opt-in-status",Values="opted-in","opt-in-not-required" \
      # --query "Regions[].RegionName|sort(@)" | jq --compact-output
      ["af-south-1", "ap-east-1", "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ap-southeast-3", "ca-central-1", "eu-central-1", "eu-central-2", "eu-north-1", "eu-south-1", "eu-west-1", "eu-west-2", "eu-west-3", "me-central-1", "me-south-1", "sa-east-1", "us-east-1", "us-east-2", "us-west-1", "us-west-2"]
    , var.region)
    error_message = "You can't deploy in region ${var.region}."
  }
}

Surely there’s a cleaner way?

Hi @bobsut,

The variable validation feature is intended for checking if the variable is syntactically correct in isolation, such as if it is a string of appropriate syntax or if it’s from a fixed set of values encoded in the configuration. This is what allows terraform validate to work offline without credentials.

However, what you tried here could be a good use for Preconditions or Postconditions.

This situation is a little awkward for preconditions and postconditions because presumably nothing else in your module naturally depends on this data block and so you may need to use depends_on strategically on the resources that depend directly on this input variable so that they’d also depend on the data resource, since that will ensure that any postconditions in that block must pass to allow the downstream resources to work. This is an example of a “hidden dependency” that Terraform cannot infer automatically through your references in expressions.