Skip to content

Commit

Permalink
Improve backend check (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
unguiculus authored Apr 26, 2020
1 parent 2f6983a commit fe1e75d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
5 changes: 2 additions & 3 deletions cmd/gotf/gotf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,8 @@ myvar = value for compute
{
args: []string{"-d", "-c", "testdata/test-config.yaml", "-p", "environment=dev", "-m", "testdata/01_networking", "plan", "-input=false", "-no-color"},
want: []string{
"Configured backend does not match current environment",
"Got: .terraform/terraform-networking-prod.tfstate",
"Want: .terraform/terraform-networking-dev.tfstate",
"configured backend does not match current environment",
"path: got=.terraform/terraform-networking-prod.tfstate, want=.terraform/terraform-networking-dev.tfstate",
"Run terraform init -reconfigure!",
},
wantErr: true,
Expand Down
17 changes: 10 additions & 7 deletions pkg/tf/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func (tf *Terraform) checkBackendConfig(args ...string) error {
}

backendFile := filepath.Join(tf.moduleDir, ".terraform", "terraform.tfstate")
bytes, err := ioutil.ReadFile(backendFile)
b, err := ioutil.ReadFile(backendFile)
if err != nil {
if os.IsNotExist(err) {
return nil
Expand All @@ -123,22 +123,25 @@ func (tf *Terraform) checkBackendConfig(args ...string) error {
}

var backendJson map[string]interface{}
if err := json.Unmarshal(bytes, &backendJson); err != nil {
if err := json.Unmarshal(b, &backendJson); err != nil {
return err
}

sb := strings.Builder{}
for k, v := range tf.config.BackendConfigs {
b := backendJson["backend"].(map[string]interface{})
c := b["config"].(map[string]interface{})
currentVal := c[k]
if v != currentVal {
return fmt.Errorf(`Configured backend does not match current environment
Got: %s
Want: %s
Run terraform init -reconfigure!`, currentVal, v)
sb.WriteString(fmt.Sprintf("%s: got=%v, want=%v\n", k, currentVal, v))
}
}

if sb.Len() > 0 {
sb.WriteString("\nRun terraform init -reconfigure!\n")
return fmt.Errorf("configured backend does not match current environment\n\n%s", sb.String())
}

return nil
}

Expand Down

0 comments on commit fe1e75d

Please sign in to comment.