Python HCL2 Parser

8.1.1 · active · verified Thu Apr 09

python-hcl2 is a robust parser for HCL2 (HashiCorp Configuration Language v2), primarily used for Terraform configuration files. It converts HCL2 code into Python data structures (lists of dictionaries) and supports reverse transformation from Python dicts back to HCL2. The current version is 8.1.1, with a release cadence that has seen frequent updates, especially around the major v8.0.0 overhaul.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing an HCL2 configuration string using `hcl2.loads()` and then serializing the resulting Python list of dictionaries back into an HCL2 string using `hcl2.dumps()`. It highlights the v8 breaking change where parsing now returns a list of dictionaries.

import hcl2
import json

hcl2_config = '''
resource "aws_s3_bucket" "example" {
  bucket = "my-unique-bucket-name"
  acl    = "private"

  tags = {
    Environment = "Development"
    Project     = "MyApp"
  }
}

variable "region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}
'''

# Parse the HCL2 string
parsed_data = hcl2.loads(hcl2_config)

# Print the parsed data (v8 returns a list of dictionaries)
print("--- Parsed Data (Python List of Dicts) ---")
print(json.dumps(parsed_data, indent=2))

# Accessing specific blocks (example: the first resource block)
if parsed_data and 'resource' in parsed_data[0]:
    resource_block = parsed_data[0]['resource']['aws_s3_bucket']['example']
    print("\n--- Extracted Resource Block ---")
    print(json.dumps(resource_block, indent=2))

# Serialize back to HCL2 (v8 feature)
recreated_hcl2 = hcl2.dumps(parsed_data)
print("\n--- Recreated HCL2 ---")
print(recreated_hcl2)

view raw JSON →