Variables

A variable is set at runtime, allowing us to vary Terraform's behaviour.

  • Therefore, if Terraform were a function, a variable would be an input to the function.
  • note: not to be confused with locals, which themselves are actually more like variables as used in general programming

*.tfvars is for giving the actual variable values during execution. It allows you to customize the specific execution. A good example will be variable values that are specific to an environment like number to vms or the type/tier/sku of a database and similar.

  • variables defined in this file override the defaults specified in variables.tf

Since you can supply files on the command line you can have scenarios where you supply different *.tfvars file like

terraform plan --file-name dev.tfvars

terraform plan --file-name prod.tfvars
variable "bucket_name" {
    type = string
    # describe what this variable is used for
    description = "the name of the bucket we are creating"
    default = "default_bucket_name"
}

resource "aws_s3_bucket" "bucket" {
    bucket = var.bucket_name
}

Variables can be more complex too:

instance_map = {
    dev = "t3.small"
    test = "t3.medium"
    prod = "t3.large"
}

environment_type = "dev"

And referenced like:

variable "instance_map" {
    type = map(string)
}
variable "environment_type" {}

output "selected_instance" {
    value = var.instance_map[var.environment_type]
}

Types

  • string
  • bool
  • number
  • list(<TYPE>)
  • set(<TYPE>)
    • each value is unique
  • map(<TYPE>)
  • object()
    • like a map, but values can be different types
  • tuple([<TYPE>, …])
    • number of values and order is preserved
  • any
    • unlike any type from Typescript; this any allows Terraform to infer based on the actual value.

Providing variables (4 ways)

  1. When we run terraform init and terraform apply, we will be prompted to provide a value for the variable(s).

  2. pass the value with:

terraform apply -var bucket_name=my_bucket
  1. export environment variables in the terminal prefixed with TF_VAR_:
export TF_VAR_bucket_name=my_bucket
  1. create a terraform.tfvars file (or <ANYNAME>.auto.tfvars):
bucket_name = "my_bucket"

Backlinks