Python HCL2 Parser
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
- breaking Starting with version 8.0.0, the `hcl2.load()` and `hcl2.loads()` functions now return a list of dictionaries instead of a single dictionary. This change better represents HCL2's top-level block structure.
- gotcha While `python-hcl2` offers robust parsing, HCL2's dynamic features like interpolation (`${...}`), template directives (`%{if ...}`), and complex expressions can still lead to parsing nuances. Edge cases may not always be perfectly represented as standard Python data structures or round-trip identically.
- gotcha Round-tripping (parsing HCL2 to Python then serializing back to HCL2) might not preserve original formatting, comments, or all subtle syntactic nuances present in the source HCL2 file. While v8 significantly improved bidirectional conversion, a perfect byte-for-byte fidelity is not guaranteed.
Install
-
pip install python-hcl2
Imports
- load
import hcl2 parsed_data = hcl2.load(file_object)
- loads
import hcl2 parsed_data = hcl2.loads(hcl2_string)
- dumps
import hcl2 hcl2_string = hcl2.dumps(python_dict_list)
Quickstart
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)