diff --git a/command/build_test.go b/command/build_test.go index cb24f15cd..d912e1319 100644 --- a/command/build_test.go +++ b/command/build_test.go @@ -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 }, }, diff --git a/command/test-fixtures/hcl/variables/ref_non_existing/ref_non_existing_var.pkr.hcl b/command/test-fixtures/hcl/variables/ref_non_existing/ref_non_existing_var.pkr.hcl new file mode 100644 index 000000000..e005230b4 --- /dev/null +++ b/command/test-fixtures/hcl/variables/ref_non_existing/ref_non_existing_var.pkr.hcl @@ -0,0 +1,7 @@ +source "null" "test" { + communicator = "none" +} + +build { + sources = ["null.test"] +} diff --git a/command/test-fixtures/hcl/variables/ref_non_existing/variables.auto.pkrvars.hcl b/command/test-fixtures/hcl/variables/ref_non_existing/variables.auto.pkrvars.hcl new file mode 100644 index 000000000..ae45fb425 --- /dev/null +++ b/command/test-fixtures/hcl/variables/ref_non_existing/variables.auto.pkrvars.hcl @@ -0,0 +1 @@ +testvar = "auto" diff --git a/hcl2template/types.variables.go b/hcl2template/types.variables.go index 6cb4977e0..9131d5f33 100644 --- a/hcl2template/types.variables.go +++ b/hcl2template/types.variables.go @@ -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