hcl2: add example for undefined variable set warn

When a variable is set in a pkrvars file, but isn't defined, an error
message is output, but does not deliver an example of what is expected
by Packer in order to complete a build.

To remedy that, we improve the error message by giving an example of
variable block to include in the build template.
pull/12016/head
Lucas Bajolet 4 years ago committed by Lucas Bajolet
parent f6e31d3147
commit 61c56e161c

@ -1138,6 +1138,37 @@ func TestBuildCmd(t *testing.T) {
nbErrs)
}
return nil
},
},
{
name: "hcl - undefined var set in pkrvars",
args: []string{
testFixture("hcl", "variables", "ref_non_existing"),
},
expectedCode: 0,
outputCheck: func(out, err string) error {
if !strings.Contains(out, "Warning: Undefined variable") {
return fmt.Errorf("expected 'Warning: Undefined variable' in output, did not find it")
}
nbWarns := strings.Count(out, "Warning: ")
if nbWarns != 1 {
return fmt.Errorf(
"error: too many warnings in build output, expected 1, got %d",
nbWarns)
}
if !strings.Contains(out, "variable \"testvar\" {") {
return fmt.Errorf("missing definition example for undefined variable")
}
nbErrs := strings.Count(err, "Error: ")
if nbErrs != 0 {
return fmt.Errorf("error: expected build to succeed without errors, got %d",
nbErrs)
}
return nil
},
},

@ -0,0 +1,7 @@
source "null" "test" {
communicator = "none"
}
build {
sources = ["null.test"]
}

@ -666,11 +666,14 @@ func (cfg *PackerConfig) collectInputVariableValues(env []string, files []*hcl.F
diags = append(diags, &hcl.Diagnostic{
Severity: sev,
Summary: "Undefined variable",
Detail: fmt.Sprintf("A %q variable was set but was "+
"not found in known variables. To declare "+
"variable %q, place this block in one of your "+
".pkr files, such as variables.pkr.hcl",
name, name),
Detail: fmt.Sprintf("A %[1]q variable was set but was "+
"not declared as an input variable. To declare "+
"variable %[1]q, place this block in one of your "+
".pkr.hcl files, such as variables.pkr.hcl\n\n"+
"variable %[1]q {\n"+
" type = string\n"+
"}",
name),
Context: attr.Range.Ptr(),
})
continue

Loading…
Cancel
Save