HCL2 Parser

0.4.3 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to parse HCL2 content from a file into a Python dictionary using `hcl2.load()`.

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')

view raw JSON →