Convert Nested HCL Blocks to JSON

Understand how nested HCL blocks translate to nested JSON objects. Covers inner blocks like provisioner, lifecycle, and connection within resource blocks.

Basic Syntax

Detailed Explanation

Nested Blocks in HCL

HCL supports blocks nested inside other blocks. Each nested block becomes a nested JSON object within its parent. This pattern is common in Terraform for configuration sections like provisioner, lifecycle, connection, and dynamic blocks.

Example HCL

resource "aws_instance" "web" {
  ami           = "ami-abc123"
  instance_type = "t3.medium"

  root_block_device {
    volume_size = 50
    volume_type = "gp3"
    encrypted   = true
  }

  lifecycle {
    create_before_destroy = true
    prevent_destroy       = false
  }
}

How Nesting Works

In JSON, nested blocks become nested objects within their parent block's object. The block type name becomes the key, and the block body becomes the value object.

{
  "resource": {
    "aws_instance": {
      "web": {
        "ami": "ami-abc123",
        "instance_type": "t3.medium",
        "root_block_device": {
          "volume_size": 50,
          "volume_type": "gp3",
          "encrypted": true
        },
        "lifecycle": {
          "create_before_destroy": true,
          "prevent_destroy": false
        }
      }
    }
  }
}

Multiple Nested Blocks

When multiple blocks of the same type appear (e.g., multiple provisioner blocks), they are collected into a JSON array. Single blocks remain as objects.

Depth Limits

There is no practical limit to nesting depth. Blocks can contain blocks that contain blocks, and the JSON output faithfully mirrors the nesting structure.

Use Case

Working with Terraform resources that have complex nested configurations, such as AWS EC2 instances with block device mappings, ECS task definitions with container configurations, or any resource that uses lifecycle rules and provisioners.

Try It — HCL ↔ JSON Converter

Open full tool