Define an AWS Region Variable with Validation
Create a Terraform variable for AWS region selection with regex validation ensuring only valid AWS region codes are accepted.
Detailed Explanation
AWS Region Variable with Validation
One of the most common Terraform variables is the AWS region. Rather than hardcoding the region in your provider block, defining it as a variable lets you deploy the same infrastructure to different regions without modifying code.
Variable Definition
variable "aws_region" {
type = string
description = "The AWS region to deploy resources in"
default = "us-east-1"
validation {
condition = can(regex("^(us|eu|ap|sa|ca|me|af)-(north|south|east|west|central|southeast|northeast)-[0-9]+$", var.aws_region))
error_message = "Must be a valid AWS region (e.g., us-east-1, eu-west-2)."
}
}
tfvars Usage
aws_region = "eu-west-1"
Key Points
- The
can(regex(...))pattern returnstrueif the regex matches andfalseotherwise, without raising an error - The regex covers all AWS region naming conventions: continent prefix, direction, and zone number
- A sensible default (
us-east-1) means the variable is optional — callers can override it but don't have to - This validation catches typos early during
terraform planrather than at AWS API call time
Common Alternatives
Some teams prefer an allowed_values approach using contains() instead of regex, explicitly listing the regions they've approved:
validation {
condition = contains(["us-east-1", "us-west-2", "eu-west-1", "eu-central-1"], var.aws_region)
error_message = "Only approved regions are allowed."
}
This is stricter and better for organizations that restrict deployments to specific regions for compliance.
Use Case
Multi-region deployments where the same Terraform configuration needs to target different AWS regions across environments (dev in us-east-1, prod in eu-west-1).
Try It — Terraform Variable Generator
Related Topics
Define EC2 Instance Type with Allowed Values
AWS Basics
Define VPC CIDR Block Variable with CIDR Validation
AWS Basics
Define Environment Name Variable with Allowed Values
Common Patterns
Define Common Tags as a map(string) Variable
Common Patterns
Define Availability Zones Variable for Multi-AZ Deployment
AWS Basics