Variables

Variables

A variable is an input to a Terraform configuration or a Terraform module.

Variables are conventionally declared in a file named variables.tf1. Declare variables using variable blocks:

variables.tf
1
2
3
4
5
variable "name" {
  description = "The name of a person"
  default     = "Jane Doe"
  type        = string
}

A variable has a type to indicate what type of value Terraform can expect for this variable. There are three basic types:

  • string
  • bool (true or false)
  • number (used for both integers and decimal numbers, e.g. 1, -1242, and 3.1415)

There are also four composite types:

  • object()
  • map()
  • list()
  • tuple()

If you need to pass sensitive data (e.g. passwords) into a Terraform configuration or module you should specify that the variable is sensitive:

variables.tf
1
2
3
4
5
variable "password" {
  description = "Database password"
  type        = string
  sensitive   = true
}

If you expect a value for a variable to fulfill certain conditions you can add one or more validation blocks to the variable:

variables.tf
1
2
3
4
5
6
7
8
9
variable "region" {
  description = "Cloud region name"
  type        = string
  
  validation {
    condition     = contains(["us", "eu"], var.region)
    error_message = "Cloud region is expected to be us or eu."
  }
}

If the value passed to the region variable is not one of us or eu, Terraform will not proceed and will instead print the error_message.

You reference the value of a variable using the var.<name> syntax. An example of what this could look like:

main.tf
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
variable "filename" {
  description = "Filename of the configuration file to create"
  default     = "server.hcl"
  type        = string
}

resource "local_file" "config" {
  filename = var.filename
  content  = <<-EOF
    # omitted ...
  EOF>>
}

Best practices

  • Add the default argument to variables if a sensible default value exist.
  • Declare sensitive values using the sensitive = true argument.
  • Add the description argument with a descriptive value to tell users what this variable is.

  1. This is not a requirement. You can place variables in any Terraform file inside of your Terraform configuration. However, you should follow the convention of using variables.tf to not surprise and confuse other users of the Terraform configuration. ↩︎