Course contentsShow
← Cloud and Infrastructure
Lesson 735 of 2,98914. Terraform FundamentalsFree lesson

Expressions and Operators

Using arithmetic, comparison, and logical operators in HCL expressions for dynamic configurations.

Expressions and Operators

You'll learn how to use arithmetic, comparison, and logical operators in HCL to create dynamic, conditional infrastructure configurations.

What Are Expressions in HCL?

Expressions in HCL (HashiCorp Configuration Language) are the building blocks that compute values. Think of them like formulas in a spreadsheet—you combine variables, values, and operators to produce results that make your infrastructure configuration smart and flexible.

Arithmetic Operators

You can perform math directly in your Terraform code:

resource "aws_instance" "example" {
  count = 2 + 3  # Result: 5 instances
}

locals {
  total_storage = 100 * 2      # 200 GB
  half_capacity = 50 / 2       # 25
  remainder     = 10 % 3       # 1
}

Comparison Operators

Compare values to make decisions:

locals {
  is_production   = var.environment == "prod"  # Equal to
  needs_upgrade   = var.memory != 8            # Not equal to
  exceeds_limit   = var.instances > 10         # Greater than
  within_budget   = var.cost <= 1000           # Less than or equal
}

Logical Operators

Combine conditions using && (and), || (or), and ! (not):

locals {
  deploy_safely = var.environment == "prod" && var.backup_enabled
  needs_alert   = var.cpu_usage > 80 || var.memory_usage > 90
  not_test      = !var.is_test
}

These operators let you write conditional logic that adapts your infrastructure based on variables and environment requirements—like deciding whether to create a resource only when it's production and backups are enabled.

Key Takeaway: Arithmetic, comparison, and logical operators transform static configurations into dynamic ones, allowing Terraform to make decisions and calculations based on your input variables and resource attributes.