Skip to content

Commit

Permalink
hcl2: handle unquoted undefined variables (#10419)
Browse files Browse the repository at this point in the history
This fixes a regression in #10326, to handle unquoted unknown variables.

The HCL job may contain unquoted undefined variable references without ${...} wrapping, e.g. value = meta.node_class. In 1.0.4, this got parsed as value = "${meta.node_class}".

This code performs a scan to find the relevant ${ and }, and only tries to find the closest ones with whitespace as the only separator.
  • Loading branch information
Mahmood Ali authored and schmichael committed May 14, 2021
1 parent 750e7b1 commit 5df8124
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
15 changes: 15 additions & 0 deletions jobspec2/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -873,4 +873,19 @@ func TestParse_UndefinedVariables(t *testing.T) {
require.Equal(t, c, *job.Region)
})
}

t.Run("unquoted", func(t *testing.T) {
hcl := `job "example" {
region = meta.mytest
}`

job, err := ParseWithConfig(&ParseConfig{
Path: "input.hcl",
Body: []byte(hcl),
})
require.NoError(t, err)

require.Equal(t, "${meta.mytest}", *job.Region)

})
}
33 changes: 23 additions & 10 deletions jobspec2/types.config.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package jobspec2

import (
"bytes"
"fmt"
"strings"

Expand Down Expand Up @@ -315,18 +314,32 @@ func (c *jobConfig) EvalContext() *hcl.EvalContext {
end := t.SourceRange().End.Byte

v := string(body[start:end])
if i := bytes.IndexByte(body[end:], '}'); i != -1 {
v += string(body[end : end+i+1])
} else {
// fallback for unexpected cases
v += "}"

// find the start of inclusing "${..}" if it's inclused in one; otherwise, wrap it in one
isBracketed := false
for i := start - 1; i >= 1; i-- {
if body[i] == '{' && body[i-1] == '$' {
isBracketed = true
v = string(body[i-1:start]) + v
break
} else if body[i] != ' ' {
break
}
}

if i := bytes.LastIndex(body[:start], []byte("${")); i != 0 {
v = string(body[i:start]) + v
if isBracketed {
for i := end + 1; i < len(body); i++ {
if body[i] == '}' {
v += string(body[end:i])
} else if body[i] != ' ' {
// unexpected!
v += "}"
break
}
}

} else {
// fallback for unexpected cases
v = "${" + v
v = "${" + v + "}"
}

return cty.StringVal(v), nil
Expand Down

0 comments on commit 5df8124

Please sign in to comment.