cli: Improved error for invalid -var "foo = bar"

When specifying variable values on the command line, name-value pairs
must be joined with an equals sign, without surrounding spaces.
Previously Terraform would interpret "foo = bar" as assigning the value
" bar" to the variable named "foo ". This is never valid, as variable
names may not include whitespace.

This commit looks for this specific error and returns a diagnostic with
a suggestion for correcting it. We cannot simply trim whitespace,
because it is valid to write "foo= bar" to assign the value " bar" to
the variable "foo", as unlikely as it seems.
This commit is contained in:
Alisdair McDiarmid 2022-05-03 09:14:29 -04:00
parent 80792312d8
commit 91d75baba1
2 changed files with 53 additions and 0 deletions

View File

@ -102,6 +102,14 @@ func (m *Meta) collectVariableValues() (map[string]backend.UnparsedVariableValue
}
name := raw[:eq]
rawVal := raw[eq+1:]
if strings.HasSuffix(name, " ") {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Invalid -var option",
fmt.Sprintf("Variable name %q is invalid due to trailing space. Did you mean -var=\"%s=%s\"?", name, strings.TrimSuffix(name, " "), strings.TrimPrefix(rawVal, " ")),
))
continue
}
ret[name] = unparsedVariableValueString{
str: rawVal,
name: name,

View File

@ -575,6 +575,51 @@ func TestPlan_vars(t *testing.T) {
}
}
func TestPlan_varsInvalid(t *testing.T) {
testCases := []struct {
args []string
wantErr string
}{
{
[]string{"-var", "foo"},
`The given -var option "foo" is not correctly specified.`,
},
{
[]string{"-var", "foo = bar"},
`Variable name "foo " is invalid due to trailing space.`,
},
}
// Create a temporary working directory that is empty
td := t.TempDir()
testCopyDir(t, testFixturePath("plan-vars"), td)
defer testChdir(t, td)()
for _, tc := range testCases {
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
p := planVarsFixtureProvider()
view, done := testView(t)
c := &PlanCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(p),
View: view,
},
}
code := c.Run(tc.args)
output := done(t)
if code != 1 {
t.Fatalf("bad: %d\n\n%s", code, output.Stdout())
}
got := output.Stderr()
if !strings.Contains(got, tc.wantErr) {
t.Fatalf("bad error output, want %q, got:\n%s", tc.wantErr, got)
}
})
}
}
func TestPlan_varsUnset(t *testing.T) {
// Create a temporary working directory that is empty
td := t.TempDir()