diff --git a/pkg/terraform/executor.go b/pkg/terraform/executor.go index 5900b0ec4..098e3b6fa 100644 --- a/pkg/terraform/executor.go +++ b/pkg/terraform/executor.go @@ -518,25 +518,22 @@ func (ex *Executor) logPath(id int) string { } func (ex *Executor) checkVersion() error { - vOutput, err := ex.executeSync("--version") + versionOutputRaw, err := ex.executeSync("version", "-json") if err != nil { - return fmt.Errorf("executing 'terraform --version': %w", err) + return fmt.Errorf("executing 'terraform version -json': %w", err) } - format := "Terraform v%s\n" - var vStr string - n, err := fmt.Sscanf(string(vOutput), format, &vStr) - if err != nil { - return fmt.Errorf("output %q does not match format %q: %w", string(vOutput), format, err) - } + versionOutput := struct { + TerraformVersion string `json:"terraform_version"` + }{} - if n != 1 { - return fmt.Errorf("version not found in 'terraform --version' output") + if err := json.Unmarshal(versionOutputRaw, &versionOutput); err != nil { + return fmt.Errorf("unmarshaling version command output %q: %w", string(versionOutputRaw), err) } - v, err := version.NewVersion(vStr) + v, err := version.NewVersion(versionOutput.TerraformVersion) if err != nil { - return fmt.Errorf("parsing Terraform version %q: %w", vStr, err) + return fmt.Errorf("parsing Terraform version %q: %w", versionOutput.TerraformVersion, err) } // requiredVersion is const, so we test it in unit tests. diff --git a/pkg/terraform/executor_test.go b/pkg/terraform/executor_test.go index 67edd7001..3185eb355 100644 --- a/pkg/terraform/executor_test.go +++ b/pkg/terraform/executor_test.go @@ -31,21 +31,50 @@ func TestVersionConstraint(t *testing.T) { expectError bool }{ "valid": { - output: "Terraform v0.13.10", + output: `{ + "terraform_version": "0.13.10", + "terraform_revision": "", + "provider_selections": {}, + "terraform_outdated": false +} +`, }, "outdated": { - output: "Terraform v0.11.0", + output: `{ + "terraform_version": "0.11.0", + "terraform_revision": "", + "provider_selections": {}, + "terraform_outdated": false +} +`, expectError: true, }, "unsupported": { - output: "Terraform v0.14.5", + output: `{ + "terraform_version": "0.14.5", + "terraform_revision": "", + "provider_selections": {}, + "terraform_outdated": false +} +`, expectError: true, }, - "with extra test": { + "not JSON": { output: `Terraform v0.13.11 Your version of Terraform is out of date! The latest version is 0.13.3. You can update by downloading from https://www.terraform.io/downloads.html`, + expectError: true, + }, + "empty version field": { + output: `{ + "terraform_version": "", + "terraform_revision": "", + "provider_selections": {}, + "terraform_outdated": false +} +`, + expectError: true, }, }