Skip to content

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:

  1. string
  2. number
  3. bool
  4. list()
  5. set()
  6. map()
  7. object({...})
  8. tuple([...])

Using Variables

Reference variables in your configuration using the var. prefix:

resource "aws_instance" "example" {
  instance_type = var.instance_type
}

Setting Variable Values

  1. In a .tfvars file
  2. On the command line: -var="instance_type=t2.small"
  3. 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.