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.
pip install python-hcl2Verified import paths — ran on the pinned version, not inferred.
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.
Update your code to iterate over the returned list or access elements by index. For example, `hcl2.loads(s)[0]` if you expect a single top-level block, or iterate `for block in hcl2.loads(s): ...`.
Consult the 'Limitations' section in the official documentation for known quirks. Thoroughly test parsing and serialization with your specific HCL2 configurations, especially those with advanced interpolation or conditional logic, to ensure expected behavior.
If exact HCL2 formatting preservation is critical (e.g., for version control systems comparing files), consider using specialized HCL2 formatting tools externally or validate the output of `hcl2.dumps()` carefully. For programmatic manipulation where logical correctness is paramount, `hcl2.dumps()` is generally reliable.