hcl-rs icon indicating copy to clipboard operation
hcl-rs copied to clipboard

Understanding where `EvalError::NoSuchKey` comes from

Open vlad-ivanov-name opened this issue 6 months ago • 1 comments

Follow-up to https://github.com/martinohmann/hcl-rs/issues/184.

Consider a terraform-like environment where local variables can be defined in locals blocks and where locals can reference each other. One way to resolve those references would be to evaluate values in a loop, every time topologically sorting the graph of references and evaluating more missing values.

Variables are referenced through an object local, e.g. local.variable_name. Right now if the variable is not defined in the evaluation context, the library will return the following error:

https://github.com/martinohmann/hcl-rs/blob/796707ab4ebfe6b83996aef4cce8d58ae2d51ced/crates/hcl-rs/src/eval/error.rs#L208-L209

The problem is, it's not clear what expression triggered the error. In the following code:

locals {
  var_combined = "${local.var_a}-${something.var_a}"
  var_a = "a"
}

the error will be something like:

        EvalError(
            "var_combined",
            Error {
                inner: ErrorInner {
                    kind: NoSuchKey(
                        "var_a",
                    ),
                    expr: Some(
                        TemplateExpr(
                            QuotedString(
                                "${local.var_a}-${something.var_a}",
                            ),
                        ),
                    ),
                },
            },
        )

with this error it seems to be impossible to tell whether the var_a key is missing from local object, or from some other object in code.

would it be possible to include the expression that produced the object itself in the error? or somehow else keep track of the source?

vlad-ivanov-name avatar Dec 15 '23 14:12 vlad-ivanov-name