Format Locals Block with Complex Expressions

Format Terraform locals blocks containing maps, merge functions, conditional expressions, and for expressions with proper alignment and indentation.

Variables & Outputs

Detailed Explanation

Formatting Locals Blocks

The locals block is where you define computed values, merge maps, and build complex data structures. These blocks often contain the most complex expressions in a Terraform configuration, making formatting critical for readability.

Example Locals Block

locals {
  environment = var.environment
  project     = var.project_name
  region      = var.aws_region

  common_tags = {
    Environment = local.environment
    Project     = local.project
    ManagedBy   = "terraform"
    Team        = var.team_name
  }

  resource_prefix = "${local.project}-${local.environment}"

  subnet_cidrs = {
    public  = [for i in range(3) : cidrsubnet(var.vpc_cidr, 8, i)]
    private = [for i in range(3) : cidrsubnet(var.vpc_cidr, 8, i + 10)]
    data    = [for i in range(3) : cidrsubnet(var.vpc_cidr, 8, i + 20)]
  }

  is_production = local.environment == "production"

  instance_type = local.is_production ? "m5.xlarge" : "t3.medium"

  merged_tags = merge(
    local.common_tags,
    var.additional_tags,
    {
      LastUpdated = timestamp()
    }
  )
}

Formatting Details

  • Simple assignments aligned: environment, project, region have aligned = signs
  • Map values aligned: Within common_tags, keys and values line up
  • For expressions: [for i in range(3) : ...] stays on one line when short enough
  • Conditional expressions: Ternary ? : stays on one line for simple conditions
  • Function calls: merge() arguments are each on their own line with indentation
  • Blank line separation: Logical groups of locals are separated by blank lines

Use Case

Computing derived values, building tag maps, calculating CIDR blocks, and defining environment-specific settings in a central locals block.

Try It — Terraform HCL Formatter

Open full tool