variables
Learn how to define, call, and validate Terraform variables. Master variable usage for flexible infrastructure as code.
Terraform Variables
Terraform variables are essential for making your infrastructure configurations dynamic and reusable. They allow you to pass values into your Terraform modules, enabling customization without altering the core code. This guide covers defining, calling, and validating variables in Terraform.
Define Terraform Variables
You define variables within a variables.tf
file (or any .tf
file) using the variable
block. Each variable should have a unique name and can optionally include a default
value, description
, type
, and validation
block.
$ cat variables.tf
variable "environment" {
description = "The deployment environment (e.g., dev, staging, prod)."
type = string
default = "prod"
}
variable "name" {
description = "A name prefix for resources."
type = string
default = "web"
}
Call Terraform Variables
Variables are accessed within your Terraform configuration using the var
object, like var.variable_name
. You can use them in resource configurations, outputs, or within the Terraform console for testing.
To interactively test variable values, you can use the terraform console
command:
$ terraform console
> var.name
"web"
> var.environment
"prod"
You can also use variables to construct dynamic strings, for example, by combining them with other strings or using Terraform's built-in functions like format
.
Example using format
function:
> format("%s-%s-server", var.name, var.environment)
"web-prod-server"
For more information on string formatting and other functions, refer to the official Terraform documentation: Terraform Format Function.
Validate Terraform Variables
The validation
block within a variable
definition allows you to enforce specific conditions on the variable's value before Terraform proceeds. This is crucial for ensuring data integrity and preventing misconfigurations.
Example: Validating an EC2 instance type using a regular expression:
variable "instance_type" {
description = "Instance type for EC2."
type = string
default = "t2.medium"
validation {
condition = can(regex("^[Tt][2-3].(nano|micro|small|medium|large|xlarge|2xlarge|4xlarge|8xlarge|12xlarge|16xlarge|24xlarge)$", var.instance_type))
error_message = "Instance type must be a valid EC2 instance type (e.g., t2.nano, t3.medium)."
}
}
This validation ensures that the provided instance_type
matches a common pattern for EC2 instance types. If the condition evaluates to false, Terraform will return the specified error_message
.