HCL Configuration Parser
pyhcl is a Python library for parsing HCL (HashiCorp Configuration Language) files and strings into Python dictionaries. It aims to be compatible with HCL versions commonly used by tools like Terraform. The library is currently at version 0.4.5 and is actively maintained with bug fixes and compatibility updates, though releases are irregular.
Warnings
- breaking pyhcl dropped support for Python 2 in version 0.3.0. Users on older Python 2 environments must upgrade their Python version or use pyhcl < 0.3.0.
- breaking The return type of `hcl.load` and `hcl.loads` changed significantly in version 0.2.0. Previously, it returned a custom `hcl.parser.HCL` object; now, it returns a standard Python `dict`. Code expecting the old object structure will break.
- gotcha The primary module for importing is `hcl`, not `pyhcl`. Developers sometimes try `from pyhcl import hcl` or `from pyhcl import load`, which will result in an `ImportError`.
- gotcha While `pyhcl` aims for broad HCL compatibility, it may not perfectly support every nuance or the very latest syntax of the evolving HCL specification, especially complex expressions or new language features introduced in newer HCL versions.
Install
-
pip install pyhcl
Imports
- hcl
import hcl
Quickstart
import hcl
hcl_string = '''
variable "region" {
description = "AWS region"
type = string
default = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0abcdef1234567890"
instance_type = "t2.micro"
tags = {
Name = "HelloWorld"
}
}
'''
parsed_data = hcl.loads(hcl_string)
print(parsed_data.get('resource'))
print(parsed_data.get('variable'))