{"id":1678,"library":"python-hcl2","title":"Python HCL2 Parser","description":"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.","status":"active","version":"8.1.1","language":"en","source_language":"en","source_url":"https://github.com/amplify-education/python-hcl2","tags":["hcl2","parser","terraform","infrastructure-as-code","configuration-language","hashicorp"],"install":[{"cmd":"pip install python-hcl2","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Core parsing engine, providing grammar and lexing capabilities for HCL2. Required for all parsing operations.","package":"lark","optional":false}],"imports":[{"note":"While 'hcl2.parser' exists, the primary and recommended entry points are directly from the top-level 'hcl2' module.","wrong":"from hcl2.parser import hcl2\nparsed_data = hcl2.load(file_object)","symbol":"load","correct":"import hcl2\nparsed_data = hcl2.load(file_object)"},{"note":"The 'loads' function is used for parsing HCL2 strings directly.","symbol":"loads","correct":"import hcl2\nparsed_data = hcl2.loads(hcl2_string)"},{"note":"Introduced in v8 for serializing Python data back to HCL2 strings.","symbol":"dumps","correct":"import hcl2\nhcl2_string = hcl2.dumps(python_dict_list)"}],"quickstart":{"code":"import hcl2\nimport json\n\nhcl2_config = '''\nresource \"aws_s3_bucket\" \"example\" {\n  bucket = \"my-unique-bucket-name\"\n  acl    = \"private\"\n\n  tags = {\n    Environment = \"Development\"\n    Project     = \"MyApp\"\n  }\n}\n\nvariable \"region\" {\n  description = \"AWS region\"\n  type        = string\n  default     = \"us-east-1\"\n}\n'''\n\n# Parse the HCL2 string\nparsed_data = hcl2.loads(hcl2_config)\n\n# Print the parsed data (v8 returns a list of dictionaries)\nprint(\"--- Parsed Data (Python List of Dicts) ---\")\nprint(json.dumps(parsed_data, indent=2))\n\n# Accessing specific blocks (example: the first resource block)\nif parsed_data and 'resource' in parsed_data[0]:\n    resource_block = parsed_data[0]['resource']['aws_s3_bucket']['example']\n    print(\"\\n--- Extracted Resource Block ---\")\n    print(json.dumps(resource_block, indent=2))\n\n# Serialize back to HCL2 (v8 feature)\nrecreated_hcl2 = hcl2.dumps(parsed_data)\nprint(\"\\n--- Recreated HCL2 ---\")\nprint(recreated_hcl2)","lang":"python","description":"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."},"warnings":[{"fix":"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): ...`.","message":"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.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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.","message":"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.","severity":"gotcha","affected_versions":"All versions, particularly relevant for >=8.0.0 when using `dumps()`"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}