tfparse

0.6.19.post1 · active · verified Fri Apr 17

tfparse is a Python library providing a fast, robust parser for HCL (HashiCorp Configuration Language) and Terraform files. It leverages a Go extension for its core parsing capabilities, making it efficient for use cases like security scanning (e.g., AquaSecurity defsec). The library is actively maintained with frequent minor releases, often on a weekly or bi-weekly cadence, reflecting ongoing improvements and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a Terraform configuration string and accessing structured data from the result. For parsing entire directories, use `tfparse.load_from_path`.

from tfparse import parse

# Example Terraform configuration as a string
terraform_config = """
resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-unique-bucket-name"
  acl    = "private"

  tags = {
    Environment = "Dev"
    Project     = "tfparse-example"
  }
}

variable "region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}
"""

try:
    # Parse the HCL configuration string
    parsed_data = parse(terraform_config)
    print("Successfully parsed Terraform configuration:")
    
    # Access some parsed data, e.g., the resource block
    s3_bucket = parsed_data.get("resource", {}).get("aws_s3_bucket", {}).get("my_bucket")
    if s3_bucket:
        print(f"  Resource 'aws_s3_bucket.my_bucket' found. Bucket name: {s3_bucket.get('bucket')}")
        print(f"  Tags: {s3_bucket.get('tags')}")

    # Access a variable block
    region_var = parsed_data.get("variable", {}).get("region")
    if region_var:
        print(f"  Variable 'region' default: {region_var.get('default')}")

except Exception as e:
    print(f"Error parsing configuration: {e}")

view raw JSON →