Terraform 0.12: HCL2 and Provider Improvements

If you haven’t upgraded to Terraform 0.12 yet, now’s the time. The new HCL2 syntax is a game-changer for infrastructure code. Here’s what changed.

Infrastructure and servers
Photo by Taylor Vick on Unsplash

Major Improvements

  • First-class expressions: No more interpolation everywhere
  • For expressions: Transform collections inline
  • Dynamic blocks: Generate nested blocks programmatically
  • Improved type system: Better validation and error messages

Old vs New Syntax

# Old (0.11)
resource "azurerm_resource_group" "example" {
  name     = "${var.environment}-rg"
  location = "${var.location}"
}

# New (0.12)
resource "azurerm_resource_group" "example" {
  name     = "${var.environment}-rg"  # Interpolation still works
  location = var.location              # But not required for simple refs
}

For Expressions

# Transform list
tags = { for k, v in var.tags : k => upper(v) }

# Filter list  
enabled_users = [for u in var.users : u.name if u.is_enabled]

Dynamic Blocks

resource "azurerm_network_security_group" "example" {
  name = "example-nsg"
  
  dynamic "security_rule" {
    for_each = var.security_rules
    content {
      name      = security_rule.value.name
      priority  = security_rule.value.priority
      direction = security_rule.value.direction
    }
  }
}

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.