How to Simplify Terraform Expressions

A concise example of using Terraform expressions to improve code readability.

Expressions and code organization account for a whopping 30-40% of all Terraform and OpenTofu code organization questions on reddit/r/terraform, making them the most prevalent source of confusion.

The Problem

# Hard-to-read inline expression
resource "aws_security_group" "example" {
  name = "example"
  tags = {
    Name = "sg-${join("-", [for part in split("-", var.environment): substr(part, 0, 1)])}-${var.application}"
  }
}

The Solution

# Using locals to simplify expressions
locals {
  env_prefix = join("-", [for part in split("-", var.environment): substr(part, 0, 1)])
  sg_name    = "sg-${local.env_prefix}-${var.application}"
}

resource "aws_security_group" "example" {
  name = "example"
  tags = {
    Name = local.sg_name
  }
}

Breaking down complex expressions with locals makes code more readable and maintainable. Scalr's state explorer makes it easier to debug these expressions by providing visibility into how they're evaluated.