Terraform Variables
Introduction to Variables
Variables in Terraform allow you to parameterize your configurations, making them more flexible and reusable.
Declaring Variables
Variables are typically declared in a variables.tf
file:
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
Variable Types
Terraform supports several variable types:
- string
- number
- bool
- list(
) - set(
) - map(
) - object({...})
- tuple([...])
Using Variables
Reference variables in your configuration using the var.
prefix:
resource "aws_instance" "example" {
instance_type = var.instance_type
}
Setting Variable Values
- In a
.tfvars
file - On the command line:
-var="instance_type=t2.small"
- As environment variables:
TF_VAR_instance_type=t2.small
Variable Validation
Use validation blocks to ensure variable values meet specific criteria:
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
}
}
Remember to use variables to make your Terraform configurations more flexible and easier to maintain.