Terraform Tutorial · Terraform Language · Lesson 11 of 25

Terraform Expressions

Operators, conditional expressions, string templates and splat expressions: how to compute values in Terraform.

Operators and conditionals

Conditionals and arithmetic
variable "environment" {
  default = "prod"
}

locals {
  size     = var.environment == "prod" ? "large" : "small"
  replicas = var.environment == "prod" ? 3 : 1
  disk_gb  = local.replicas * 50
}

output "plan" {
  value = "${local.replicas} x ${local.size}, ${local.disk_gb} GB disk"
}

Output

plan = "3 x large, 150 GB disk"

Run this on your computer — see “Get Started” for setup.

The conditional expression condition ? value_if_true : value_if_false is Terraform's "if".

String templates

"${...}" interpolates a value. Heredocs (<<-EOT) write multi-line strings, and %{ for … } / %{ if … } directives loop and branch inside them:

Heredoc with a template loop
locals {
  users = ["ada", "linus", "grace"]
}

output "motd" {
  value = <<-EOT
  Welcome! Accounts on this server:
  %{ for u in local.users ~}
  - ${u}
  %{ endfor ~}
  EOT
}

Output

motd = <<EOT
Welcome! Accounts on this server:
  - ada
  - linus
  - grace

EOT

Run this on your computer — see “Get Started” for setup.

Splat expressions

aws_instance.web[*].id collects an attribute from every instance into a list, the same as [for i in aws_instance.web : i.id].

Test yourself

What does var.prod ? 3 : 1 return when var.prod is false?

  1. 3
  2. 1
  3. null
  4. false
Show answer

Answer: 1