Define Environment Name Variable with Allowed Values
Create a Terraform string variable for environment names with contains() validation limiting values to dev, staging, and prod.
Detailed Explanation
Environment Name Variable
The environment variable is a cornerstone of multi-environment Terraform setups. It controls resource naming, sizing, feature toggles, and tag values across your infrastructure.
Variable Definition
variable "environment" {
type = string
description = "Deployment environment name"
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be one of: dev, staging, prod."
}
}
Usage in Resource Naming
resource "aws_s3_bucket" "data" {
bucket = "${var.project_name}-${var.environment}-data"
}
resource "aws_instance" "app" {
instance_type = var.environment == "prod" ? "m5.large" : "t3.micro"
tags = {
Name = "${var.project_name}-${var.environment}-app"
Environment = var.environment
}
}
Conditional Configuration
The environment variable drives many infrastructure decisions:
locals {
is_prod = var.environment == "prod"
instance_count = local.is_prod ? 3 : 1
multi_az = local.is_prod ? true : false
backup_enabled = local.is_prod ? true : false
log_level = local.is_prod ? "warn" : "debug"
}
Per-Environment tfvars Files
terraform plan -var-file="environments/dev.tfvars"
terraform plan -var-file="environments/staging.tfvars"
terraform plan -var-file="environments/prod.tfvars"
Each tfvars file sets the environment along with environment-specific overrides:
# environments/prod.tfvars
environment = "prod"
instance_type = "m5.large"
min_capacity = 3
max_capacity = 10
Use Case
Multi-environment Terraform configurations where resource sizing, naming, and feature flags need to change based on the deployment target (dev, staging, prod).
Try It — Terraform Variable Generator
Related Topics
Define Project Name Variable with Naming Convention Validation
Common Patterns
Define Common Tags as a map(string) Variable
Common Patterns
Define EC2 Instance Type with Allowed Values
AWS Basics
Define an AWS Region Variable with Validation
AWS Basics
Define Auto Scaling Configuration Variables
Resource Configuration