A rust library for interacting with the Hashicorp Configuration Language (HCL).
body!
for constructing HCL data structuresserde::Deserialize
or serde::Serialize
Deserialize arbitrary HCL according to the HCL JSON Specification:
```rust 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!({ "someattr": { "foo": [1, 2], "bar": true }, "someblock": { "someblocklabel": { "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:
```rust 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() .addattribute(( "someattr", Expression::fromiter([ ("foo", Expression::from(vec![1, 2])), ("bar", Expression::Bool(true)), ]), )) .addblock( Block::builder("someblock") .addlabel("someblocklabel") .add_attribute(("attr", "value")) .build(), ) .build();
let body: Body = hcl::from_str(input).unwrap();
assert_eq!(body, expected); ```
An example to serialize some terraform configuration:
```rust use hcl::expr::Traversal; use hcl::{Block, Body, Variable};
let body = Body::builder() .addblock( Block::builder("resource") .addlabel("awssnstopicsubscription") .addlabel("my-subscription") .addattribute(( "topicarn", Traversal::builder(Variable::new("awssnstopic").unwrap()) .attr("my-topic") .attr("arn") .build(), )) .addattribute(("protocol", "sqs")) .addattribute(( "endpoint", Traversal::builder(Variable::new("awssqsqueue").unwrap()) .attr("my-queue") .attr("arn") .build(), )) .build(), ) .build();
let expected = r#" resource "awssnstopicsubscription" "my-subscription" { topicarn = awssnstopic.my-topic.arn protocol = "sqs" endpoint = awssqsqueue.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.
The eval
module
documentation contains more
details and examples for expression and template evaluation, but here's a very
short example:
```rust 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!")); ```
This crate provides a couple of macros to ease building HCL data structures. Have a look at their documentation for usage examples.
Contributions are welcome! Please read CONTRIBUTING.md
before creating a PR.
The source code of hcl-rs is released under the MIT License. See the bundled LICENSE file for details.