command/init: initialize backend even if not set in the config

We need to initialize the backend even if the config has no backend set.
This allows `init` to work when unsetting a previously set backend.
Without this, there was no way to unset a backend.
This commit is contained in:
Mitchell Hashimoto 2017-02-15 15:44:53 -08:00
parent fa2fd0bf01
commit 716132431a
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
2 changed files with 67 additions and 5 deletions

View File

@ -125,13 +125,17 @@ func (c *InitCommand) Run(args []string) int {
} }
// If we're requesting backend configuration and configure it // If we're requesting backend configuration and configure it
hasBackend := conf.Terraform != nil && conf.Terraform.Backend != nil if flagBackend {
if flagBackend && hasBackend {
header = true header = true
// Only output that we're initializing a backend if we have
// something in the config. We can be UNSETTING a backend as well
// in which case we choose not to show this.
if conf.Terraform != nil && conf.Terraform.Backend != nil {
c.Ui.Output(c.Colorize().Color(fmt.Sprintf( c.Ui.Output(c.Colorize().Color(fmt.Sprintf(
"[reset][bold]" + "[reset][bold]" +
"Initializing the backend..."))) "Initializing the backend...")))
}
opts := &BackendOpts{ opts := &BackendOpts{
ConfigPath: path, ConfigPath: path,

View File

@ -1,6 +1,7 @@
package command package command
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -236,6 +237,63 @@ func TestInit_backend(t *testing.T) {
} }
} }
func TestInit_backendUnset(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)
copy.CopyDir(testFixturePath("init-backend"), td)
defer os.RemoveAll(td)
defer testChdir(t, td)()
{
ui := new(cli.MockUi)
c := &InitCommand{
Meta: Meta{
ContextOpts: testCtxConfig(testProvider()),
Ui: ui,
},
}
// Init
args := []string{}
if code := c.Run(args); code != 0 {
t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
}
if _, err := os.Stat(filepath.Join(DefaultDataDir, DefaultStateFilename)); err != nil {
t.Fatalf("err: %s", err)
}
}
{
// Unset
if err := ioutil.WriteFile("main.tf", []byte(""), 0644); err != nil {
t.Fatalf("err: %s", err)
}
// Run it again
defer testInteractiveInput(t, []string{"yes", "yes"})()
ui := new(cli.MockUi)
c := &InitCommand{
Meta: Meta{
ContextOpts: testCtxConfig(testProvider()),
Ui: ui,
},
}
args := []string{}
if code := c.Run(args); code != 0 {
t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
}
s := testStateRead(t, filepath.Join(
DefaultDataDir, DefaultStateFilename))
if !s.Backend.Empty() {
t.Fatal("should not have backend config")
}
}
}
func TestInit_backendConfigFile(t *testing.T) { func TestInit_backendConfigFile(t *testing.T) {
// Create a temporary working directory that is empty // Create a temporary working directory that is empty
td := tempDir(t) td := tempDir(t)