Define EC2 Instance Type with Allowed Values
Create a Terraform variable for EC2 instance types with contains() validation limiting choices to approved instance families.
Detailed Explanation
EC2 Instance Type Variable
Controlling which EC2 instance types are allowed in your infrastructure prevents accidental cost overruns and ensures consistency across environments.
Variable Definition
variable "instance_type" {
type = string
description = "EC2 instance type for the compute resources"
default = "t3.micro"
validation {
condition = contains(["t3.micro", "t3.small", "t3.medium", "t3.large", "m5.large", "m5.xlarge"], var.instance_type)
error_message = "Instance type must be one of: t3.micro, t3.small, t3.medium, t3.large, m5.large, m5.xlarge."
}
}
Environment-Specific Values
# dev.tfvars
instance_type = "t3.micro"
# staging.tfvars
instance_type = "t3.medium"
# prod.tfvars
instance_type = "m5.large"
Why Use contains() Instead of Regex?
- Explicit allowlist: You see exactly which values are permitted
- Self-documenting: The error message lists all valid options
- Easy to update: Adding a new instance type is a one-line change
- No regex complexity:
contains()is simpler and less error-prone
Cost Control Pattern
For organizations with budget constraints, combine this with a local map to enforce per-environment limits:
locals {
allowed_types = {
dev = ["t3.micro", "t3.small"]
staging = ["t3.small", "t3.medium"]
prod = ["m5.large", "m5.xlarge", "m5.2xlarge"]
}
}
This pattern prevents developers from accidentally launching expensive instances in development environments.
Use Case
Enterprise Terraform modules where infrastructure costs need to be controlled by restricting available instance types per environment or team.
Try It — Terraform Variable Generator
Related Topics
Define an AWS Region Variable with Validation
AWS Basics
Define Environment Name Variable with Allowed Values
Common Patterns
Define Common Tags as a map(string) Variable
Common Patterns
Define Auto Scaling Configuration Variables
Resource Configuration
Define VPC CIDR Block Variable with CIDR Validation
AWS Basics