Crate hcl

Source
Expand description

§hcl-rs

Build Status crates.io docs.rs License: Apache 2.0 License: MIT

A rust library for interacting with the Hashicorp Configuration Language (HCL).

§Features

  • A parser for the HCL syntax specification
  • Types for all HCL structures, e.g. body, blocks and attributes
  • Supporting macros like body! for constructing HCL data structures
  • Supports the expression and template sub-languages in attribute values
  • Support for deserializing and serializing arbitrary types that implement serde::Deserialize or serde::Serialize
  • Evaluation of the HCL expression and template sub-languages

§Cargo features

  • perf: enables parser performance optimizations such as inlining of small strings on the stack. This feature is disabled by default.

§Deserialization examples

Deserialize arbitrary HCL according to the HCL JSON Specification:

use serde_json::{json, Value};

let input = r#"
    some_attr = {
      foo = [1, 2]
      bar = true
    }

    some_block "some_block_label" {
      attr = "value"
    }
"#;

let expected = json!({
    "some_attr": {
        "foo": [1, 2],
        "bar": true
    },
    "some_block": {
        "some_block_label": {
            "attr": "value"
        }
    }
});

let value: Value = hcl::from_str(input).unwrap();

assert_eq!(value, expected);

If you need to preserve context about the HCL structure, deserialize into hcl::Body instead:

use hcl::{Block, Body, Expression};

let input = r#"
    some_attr = {
      "foo" = [1, 2]
      "bar" = true
    }

    some_block "some_block_label" {
      attr = "value"
    }
"#;

let expected = Body::builder()
    .add_attribute((
        "some_attr",
        Expression::from_iter([
            ("foo", Expression::from(vec![1, 2])),
            ("bar", Expression::Bool(true)),
        ]),
    ))
    .add_block(
        Block::builder("some_block")
            .add_label("some_block_label")
            .add_attribute(("attr", "value"))
            .build(),
    )
    .build();

let body: Body = hcl::from_str(input).unwrap();

assert_eq!(body, expected);

§Serialization examples

An example to serialize some terraform configuration:

use hcl::expr::Traversal;
use hcl::{Block, Body, Variable};

let body = Body::builder()
    .add_block(
        Block::builder("resource")
            .add_label("aws_sns_topic_subscription")
            .add_label("my-subscription")
            .add_attribute((
                "topic_arn",
                Traversal::builder(Variable::new("aws_sns_topic").unwrap())
                    .attr("my-topic")
                    .attr("arn")
                    .build(),
            ))
            .add_attribute(("protocol", "sqs"))
            .add_attribute((
                "endpoint",
                Traversal::builder(Variable::new("aws_sqs_queue").unwrap())
                    .attr("my-queue")
                    .attr("arn")
                    .build(),
            ))
            .build(),
    )
    .build();

let expected = r#"
resource "aws_sns_topic_subscription" "my-subscription" {
  topic_arn = aws_sns_topic.my-topic.arn
  protocol = "sqs"
  endpoint = aws_sqs_queue.my-queue.arn
}
"#.trim_start();

let serialized = hcl::to_string(&body).unwrap();

assert_eq!(serialized, expected);

Also have a look at the other examples provided in the documentation of the ser module to learn how you can construct HCL blocks when serializing custom types.

§Expression evaluation

The eval module documentation contains more details and examples for expression and template evaluation, but here’s a very short example:

use hcl::Value;
use hcl::eval::{Context, Evaluate};
use hcl::expr::TemplateExpr;

let expr = TemplateExpr::from("Hello ${name}!");

let mut ctx = Context::new();
ctx.declare_var("name", "World");

assert_eq!(expr.evaluate(&ctx).unwrap(), Value::from("Hello World!"));

§Macros

This crate provides a couple of macros to ease building HCL data structures. Have a look at their documentation for usage examples.

§Contributing

Contributions are welcome! Please read CONTRIBUTING.md before creating a PR.

§License

The source code of hcl-rs is licensed under either of Apache License, Version 2.0 or MIT license at your option.

Re-exports§

pub use hcl_edit as edit;

Modules§

de
Deserialize HCL data to a Rust data structure.
error
The Error and Result types used by this crate.
eval
Evaluate HCL templates and expressions.
expr
Types to represent the HCL expression sub-language.
format
Format data structures as HCL.
ser
Serialize a Rust data structure into HCL data.
structure
Types to represent the HCL structural sub-language.
template
Types to represent the HCL template sub-language.
value
The Value enum, a loosely typed way of representing any valid HCL value.

Macros§

attribute
Construct an hcl::Attribute from a key and a value expression.
block
Construct an hcl::Block from a block identifier, optional block labels and a block body.
body
Construct an hcl::Body from HCL blocks and attributes.
expression
Construct an hcl::Expression from an HCL attribute value expression literal.
structure
Construct an hcl::Structure which may be either an HCL attribute or block.
value
Construct an hcl::Value from an HCL attribute value value literal.

Structs§

Attribute
Represents an HCL attribute which consists of an attribute key and a value expression.
Block
Represents an HCL block which consists of a block identifier, zero or more block labels and a block body.
Body
Represents an HCL config file body.
Identifier
Represents an HCL identifier.
InternalString
An opaque string storage which inlines small strings on the stack if the perf feature is enabled.
Number
Represents an HCL number.
Template
The main type to represent the HCL template sub-languange.

Enums§

BlockLabel
Represents an HCL block label.
Error
The error type used by this crate.
Expression
A type representing the expression sub-language. It is used in HCL attributes to specify values and in HCL templates.
ObjectKey
Represents an object key.
Structure
Represents an HCL structure.
Value
Represents any valid HCL value.

Functions§

from_body
Interpret a hcl::Body as an instance of type T.
from_reader
Deserialize an instance of type T from an IO stream of HCL.
from_slice
Deserialize an instance of type T from a byte slice.
from_str
Deserialize an instance of type T from a string of HCL text.
from_value
Convert a hcl::Value into a type T that implements serde::Deserialize.
parse
Parse a hcl::Body from a &str.
to_expression
Convert a T into hcl::Expression which is an enum that can represent any valid HCL attribute value expression.
to_string
Serialize the given value as an HCL string.
to_value
Convert a T into hcl::Value which is an enum that can represent any valid HCL value.
to_vec
Serialize the given value as an HCL byte vector.
to_writer
Serialize the given value as HCL into the IO stream.

Type Aliases§

Map
The map type used for HCL objects.
Object
The object type used in the expression sub-language.
Result
The result type used by this crate.