From 71315076c3ac64e8d1e99cd03ad89978d13b5534 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Mon, 2 Mar 2015 09:21:45 -0800 Subject: [PATCH] command: autoload terraform.tfvars.json as well [GH-1030] --- command/apply_test.go | 56 +++++++++++++++++++++++++++++++++++++++++++ command/meta.go | 8 +++++++ 2 files changed, 64 insertions(+) diff --git a/command/apply_test.go b/command/apply_test.go index 57e8c01c6..e9ff25fe8 100644 --- a/command/apply_test.go +++ b/command/apply_test.go @@ -960,6 +960,58 @@ func TestApply_varFileDefault(t *testing.T) { } } +func TestApply_varFileDefaultJSON(t *testing.T) { + varFileDir := testTempDir(t) + varFilePath := filepath.Join(varFileDir, "terraform.tfvars.json") + if err := ioutil.WriteFile(varFilePath, []byte(applyVarFileJSON), 0644); err != nil { + t.Fatalf("err: %s", err) + } + + statePath := testTempFile(t) + + cwd, err := os.Getwd() + if err != nil { + t.Fatalf("err: %s", err) + } + if err := os.Chdir(varFileDir); err != nil { + t.Fatalf("err: %s", err) + } + defer os.Chdir(cwd) + + p := testProvider() + ui := new(cli.MockUi) + c := &ApplyCommand{ + Meta: Meta{ + ContextOpts: testCtxConfig(p), + Ui: ui, + }, + } + + actual := "" + p.DiffFn = func( + info *terraform.InstanceInfo, + s *terraform.InstanceState, + c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { + if v, ok := c.Config["value"]; ok { + actual = v.(string) + } + + return &terraform.InstanceDiff{}, nil + } + + args := []string{ + "-state", statePath, + testFixturePath("apply-vars"), + } + if code := c.Run(args); code != 0 { + t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) + } + + if actual != "bar" { + t.Fatal("didn't work") + } +} + func TestApply_backup(t *testing.T) { originalState := &terraform.State{ Modules: []*terraform.ModuleState{ @@ -1150,6 +1202,10 @@ const applyVarFile = ` foo = "bar" ` +const applyVarFileJSON = ` +{ "foo": "bar" } +` + const testApplyDisableBackupStr = ` ID = bar ` diff --git a/command/meta.go b/command/meta.go index d6dc0ff8c..4745ef6a1 100644 --- a/command/meta.go +++ b/command/meta.go @@ -346,6 +346,14 @@ func (m *Meta) process(args []string, vars bool) []string { args[0] = "-" + m.autoKey args[1] = DefaultVarsFilename } + + if _, err := os.Stat(DefaultVarsFilename + ".json"); err == nil { + m.autoKey = "var-file-default" + args = append(args, "", "") + copy(args[2:], args[0:]) + args[0] = "-" + m.autoKey + args[1] = DefaultVarsFilename + ".json" + } } return args