HCL v2 Parser for JavaScript

1.0.3 · active · verified Sun Apr 19

hcl2-parser is a JavaScript library designed for parsing HashiCorp Configuration Language (HCL) version 2 strings, providing crucial utility for developers working with Terraform configurations or other systems that utilize HCLv2. It offers functions to convert HCL input into either a JSON string or a JavaScript object. A key differentiator for this package is its support for the newer HCL v2 syntax, which includes features like for-expressions, dynamic blocks, and null values, an capability often lacking in other JavaScript-based HCL parsers. The library achieves this by wrapping the Go-based `tmccombs/hcl2json` tool and transpiling the necessary Go code to JavaScript using GopherJS, resulting in a self-contained npm package. As of its initial stable release, version 1.0.3, the package includes TypeScript definitions and is primarily intended for use within Node.js environments. Its release cadence is currently nascent.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing an HCL string into both a JSON string and a JavaScript object using ESM imports, highlighting how to access specific elements.

import * as hcl from 'hcl2-parser';

const hclString = `
# Create a resource group
variable "azureRegion" {
  type = string
  default = "uksouth"
}
resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = var.azureRegion
}
`;

// Parse into a JSON string
const stringResult = hcl.parseToString(hclString);
console.log('JSON String Result:', stringResult);

// Parse into an object, accessing the actual result in array index 0
const objectResult = hcl.parseToObject(hclString);
console.log('Parsed Object Resource:', objectResult[0].resource.azurerm_resource_group);
console.log('Name:', objectResult[0].resource.azurerm_resource_group.example.name);
console.log('Location:', objectResult[0].resource.azurerm_resource_group.example.location);

view raw JSON →