Skip to content

Commit

Permalink
Support unknown variable evaluation
Browse files Browse the repository at this point in the history
Expose a callback to handle unknown variables found in hcl syntax. This is
useful in situations where the variables aren't known statically upfront.
  • Loading branch information
Mahmood Ali committed Apr 7, 2021
1 parent 4512e37 commit ccf34c5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions eval_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ type EvalContext struct {
Variables map[string]cty.Value
Functions map[string]function.Function
parent *EvalContext

// UnknownVariable handles when an unknown variable is referenced.
// This handler is experimental and may change in the future.
UnknownVariable func(Traversal) (cty.Value, error)
}

// NewChild returns a new EvalContext that is a child of the receiver.
Expand Down
12 changes: 12 additions & 0 deletions traversal.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,12 @@ func (t Traversal) TraverseAbs(ctx *EvalContext) (cty.Value, Diagnostics) {

thisCtx := ctx
hasNonNil := false
var unknownHandler func(Traversal) (cty.Value, error)
for thisCtx != nil {
if unknownHandler == nil && thisCtx.UnknownVariable != nil {
unknownHandler = thisCtx.UnknownVariable
}

if thisCtx.Variables == nil {
thisCtx = thisCtx.parent
continue
Expand All @@ -83,6 +88,13 @@ func (t Traversal) TraverseAbs(ctx *EvalContext) (cty.Value, Diagnostics) {
thisCtx = thisCtx.parent
}

if unknownHandler != nil {
v, err := unknownHandler(t)
if err == nil {
return v, nil
}
}

if !hasNonNil {
return cty.DynamicVal, Diagnostics{
{
Expand Down

0 comments on commit ccf34c5

Please sign in to comment.