HCL2 Parser
bc-python-hcl2 is a Python library that provides a parser for HashiCorp Configuration Language 2 (HCL2). It is written in Python using Lark and can be used to parse any HCL2 configuration file, such as Terraform files. This package, currently at version 0.4.3, is a fork of the original `python-hcl2` by Amplify and is officially supported by Bridgecrew. The two projects are diverging, so it's important to be aware of which specific package is being used.
Warnings
- gotcha This library (`bc-python-hcl2` by Bridgecrew) is a fork of `python-hcl2` by Amplify Education. While they share a common history, they are now diverging. Ensure you are using the correct package based on your project's needs, as their APIs or behaviors may differ in future versions.
- breaking The library explicitly supports HCL2 only and is not backwards compatible with HCL v1. Attempting to parse HCL v1 syntax will result in errors.
- gotcha Older versions or information might suggest `python-hcl2` is a read-only parser. However, current versions (including `bc-python-hcl2` 0.4.3) support writing/reconstructing HCL2 from Python dictionaries using `hcl2.dumps()`, `hcl2.dump()`, and `hcl2.Builder()`.
Install
-
pip install bc-python-hcl2
Imports
- hcl2
import hcl2
Quickstart
import hcl2
import os
hcl_content = '''
variable "region" {
description = "AWS region"
type = string
default = "us-east-1"
}
resource "aws_s3_bucket" "example" {
bucket = "my-unique-example-bucket-123"
tags = {
Name = "My bucket"
Environment = "Dev"
}
}
'''
# Create a dummy HCL file
with open('example.tf', 'w') as f:
f.write(hcl_content)
# Load HCL from a file
with open('example.tf', 'r') as f:
parsed_hcl = hcl2.load(f)
print(parsed_hcl)
# Clean up the dummy file
os.remove('example.tf')