Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท The HCL Language

Expressions, Operators and Conditionals

Master Terraform expressions: references, string interpolation, heredocs, template directives, arithmetic and logical operators, the conditional operator and common patterns.

An expression is anything on the right of an =: a literal, a reference to another value, an operator, a function call, a conditional. Expressions are what turn static configuration into something flexible, for example "use a bigger server in production" or "name the bucket after the project and the environment." This lesson covers references, strings, operators and the conditional expression. Functions and for expressions follow in the next lessons.

The hcl blocks are read-only. You can try expressions for real with terraform console once Terraform is installed; the stand-ins here imitate the ideas.

References

A reference reads a value defined elsewhere. The forms you will use every day:

Reference Meaning
var.region Input variable region
local.name Local value name
aws_instance.web.id The id attribute of a resource
aws_instance.web[0].id One instance created with count
aws_instance.web["a"].id One instance created with for_each
data.aws_ami.ubuntu.id Attribute of a data source
module.network.vpc_id Output of a module
path.module, path.root, path.cwd Filesystem paths
terraform.workspace Current workspace name
each.key, each.value, count.index Inside for_each or count resources

References do double duty. They fetch a value, and they tell Terraform about dependencies, so the referenced object is created first (Dependencies).

Strings and interpolation

Inside a double-quoted string, ${ ... } evaluates an expression and inserts its result:

HCL
locals {
  bucket_name = "${var.project}-${var.environment}-logs"
  greeting    = "Hello, ${upper(var.user)}!"
  literal     = "$${not_interpolated}"      # $${ prints ${
}

When a value is only an expression, write it without quotes: ami = data.aws_ami.ubuntu.id, not "${data.aws_ami.ubuntu.id}". The extra wrapper still works but is a leftover from Terraform 0.11 and terraform fmt plus linters flag it.

Python String interpolation (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Heredocs and templates

Multi-line strings use a heredoc: <<EOT opens, the same word on its own line closes. The indented form <<-EOT removes common leading whitespace, which keeps code tidy:

HCL
resource "aws_instance" "web" {
  user_data = <<-EOT
    #!/bin/bash
    echo "Hello from ${var.environment}" > /var/www/index.html
    systemctl start nginx
  EOT
}

Interpolation works inside heredocs. Template directives add control flow inside strings with %{ ... }:

HCL
locals {
  hosts_file = <<-EOT
    %{ for ip in var.ips ~}
    server ${ip}
    %{ endfor ~}
  EOT

  banner = "%{ if var.environment == "prod" }PRODUCTION%{ else }test%{ endif }"
}

The ~ strips adjacent whitespace and newlines so the output has no blank lines. For larger files, prefer a separate template with templatefile() (functions); it keeps scripts and configuration files readable.

Operators

Terraform has the usual operators:

Category Operators
Arithmetic + - * / % and unary -
Comparison == != < <= > >=
Logical && || !
HCL
locals {
  total_gb   = var.disks * var.disk_gb          # 4 * 50 = 200
  odd_even   = var.count_of % 2 == 0 ? "even" : "odd"
  is_prod    = var.environment == "prod"
  needs_waf  = local.is_prod && !var.internal
}

Rules to remember: arithmetic works on numbers only; == between different types is false (for example "1" == 1 is false, no automatic conversion); there are no and/or words, only && and ||; and there is no operator to compare lists (== works, but < does not).

The conditional expression

The only branching construct in expressions is the ternary condition ? true_value : false_value:

HCL
resource "aws_instance" "web" {
  instance_type = var.environment == "prod" ? "m6i.large" : "t3.micro"
  monitoring    = var.environment == "prod"
}

Both branches should produce the same type. If they differ, Terraform tries to convert one to the other (a string and a number become strings), and complains if it cannot, for example a list versus a string. Only the chosen branch is evaluated in practice, but both must be valid expressions and type-checkable.

Conditional with null is the pattern to leave an argument unset:

HCL
kms_key_id = var.encrypt ? aws_kms_key.main.arn : null

Conditional with count is the classic way to create something optionally:

HCL
resource "aws_eip" "web" {
  count    = var.assign_public_ip ? 1 : 0
  instance = aws_instance.web.id
}
Python Conditionals pick sizes and optional resources (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Attribute and index access

Square brackets and dots reach into values:

HCL
local.server.name        # object attribute
local.zones[1]           # list element
local.tags["env"]        # map element
var.ports[length(var.ports) - 1]   # last element

Reading a missing key or index is an error ("Invalid index"). Use lookup(map, key, default) or try(expr, fallback) when a key may be absent. Accessing an attribute of null is also an error; try() and the optional chaining of splats (next lesson) help.

Evaluation order and when values are known

Terraform evaluates expressions during the plan whenever it can. An expression that depends on a value only known after apply, such as a new server's ID, stays unknown and shows as (known after apply). A conditional whose condition is unknown at plan time makes the whole result unknown. Keep conditions based on variables and locals (known early) rather than on freshly computed attributes, to keep plans predictable.

Practical patterns

  • Naming: "${var.project}-${var.environment}-${var.component}", built once in locals so names stay consistent.
  • Environment maps: local.size = lookup({ prod = "large", dev = "small" }, var.environment, "small") is cleaner than nested ternaries.
  • Feature flags: a bool variable plus count = var.enabled ? 1 : 0 or null arguments.
  • Avoid deep nesting: if you write a ? b : c ? d : e, switch to a map lookup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you write a literal ${ in a Terraform string without interpolating?

    Doubling the dollar sign, $${, escapes interpolation and prints ${ literally.
  2. 2. What does var.environment == "prod" ? "m6i.large" : "t3.micro" evaluate to when environment is "dev"?

    The condition is false for dev, so the second branch is used.
  3. 3. Which expression is true?

    == compares values without automatic type conversion; only 1 == 1 has matching types and values.
  4. 4. How do you create a resource only when var.enabled is true?

    count = 0 creates no instances. There is no if argument on resources.

Summary

  • References read other values and create dependencies: var.x, local.x, type.name.attr, module.m.out.
  • ${...} interpolates in strings; use bare references when the value is only an expression; $${ escapes.
  • Heredocs hold multi-line text; %{ for } and %{ if } add template logic.
  • Operators: arithmetic, comparison and &&, ||, !; == never converts types.
  • cond ? a : b is the only branch; combine with null and count for optional arguments and resources.
  • Use lookup, try and maps instead of deeply nested conditionals.

Next: for Expressions and Splat