command/init: omit a warning if -backend-config is used with no backend (#22164)

* command/init: omit a warning if -backend-config is used with no backend
block

Terraform would silently accept - and swallow - `-backend-config` on the
CLI when there was no `backend` block. Since it is mostly expected to
override existing backend configuration, terraform
should omit a warning if there is no backend configuration to
override.

If the user intended to override the default (local) backend
configuration, they can first add a `backend` block to the `terraform` block to silence the warning (or just ignore it):

```hcl
terraform {
  backend "local" {}
}
```
This commit is contained in:
Kristin Laemmert 2019-07-23 08:08:28 -04:00 committed by GitHub
parent a02e43b86e
commit a16e1fc0a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 0 deletions

View File

@ -438,6 +438,29 @@ func (c *InitCommand) initBackend(root *configs.Module, extraConfig rawFlags) (b
if overrideDiags.HasErrors() {
return nil, true, diags
}
} else {
// If the user supplied a -backend-config on the CLI but no backend
// block was found in the configuration, it's likely - but not
// necessarily - a mistake. Return a warning.
if !extraConfig.Empty() {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Warning,
"Missing backend configuration",
`-backend-config was used without a "backend" block in the configuration.
If you intended to override the default local backend configuration,
no action is required, but you may add an explicit backend block to your
configuration to clear this warning:
terraform {
backend "local" {}
}
However, if you intended to override a defined backend, please verify that
the backend configuration is present and valid.
`,
))
}
}
opts := &BackendOpts{

View File

@ -518,6 +518,32 @@ func TestInit_backendConfigKVReInitWithConfigDiff(t *testing.T) {
}
}
func TestInit_backendCli_no_config_block(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)
copy.CopyDir(testFixturePath("init"), td)
defer os.RemoveAll(td)
defer testChdir(t, td)()
ui := new(cli.MockUi)
c := &InitCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(testProvider()),
Ui: ui,
},
}
args := []string{"-backend-config", "path=test"}
if code := c.Run(args); code != 0 {
t.Fatalf("got exit status %d; want 0\nstderr:\n%s\n\nstdout:\n%s", code, ui.ErrorWriter.String(), ui.OutputWriter.String())
}
errMsg := ui.ErrorWriter.String()
if !strings.Contains(errMsg, "Warning: Missing backend configuration") {
t.Fatal("expected missing backend block warning, got", errMsg)
}
}
func TestInit_targetSubdir(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)