command: Check required_version before upgrading

If a configuration has a version constraint which prevents use with
Terraform 0.13, the upgrade command should exit before making any
changes.
This commit is contained in:
Alisdair McDiarmid 2020-05-07 14:51:57 -04:00
parent 7209ffe9b6
commit 01a3376ead
4 changed files with 52 additions and 0 deletions

View File

@ -15,6 +15,7 @@ import (
"github.com/hashicorp/terraform/configs"
"github.com/hashicorp/terraform/internal/getproviders"
"github.com/hashicorp/terraform/tfdiags"
tfversion "github.com/hashicorp/terraform/version"
"github.com/zclconf/go-cty/cty"
)
@ -140,6 +141,27 @@ func (c *ZeroThirteenUpgradeCommand) Run(args []string) int {
))
}
// Check Terraform required_version constraints
for _, file := range files {
for _, constraint := range file.CoreVersionConstraints {
if !constraint.Required.Check(tfversion.SemVer) {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Unsupported Terraform Core version",
Detail: fmt.Sprintf(
"This configuration does not support Terraform version %s. To proceed, either choose another supported Terraform version or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.",
tfversion.String(),
),
Subject: &constraint.DeclRange,
})
}
}
}
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// Build up a list of required providers, uniquely by local name
requiredProviders := make(map[string]*configs.RequiredProvider)
var rewritePaths []string

View File

@ -220,6 +220,32 @@ func TestZeroThirteenUpgrade_skippedFiles(t *testing.T) {
}
}
func TestZeroThirteenUpgrade_unsupportedVersion(t *testing.T) {
inputPath := testFixturePath("013upgrade-unsupported-version")
td := tempDir(t)
copy.CopyDir(inputPath, td)
defer os.RemoveAll(td)
defer testChdir(t, td)()
ui := new(cli.MockUi)
c := &ZeroThirteenUpgradeCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(testProvider()),
Ui: ui,
},
}
if code := c.Run(nil); code == 0 {
t.Fatal("expected error, got:", ui.OutputWriter)
}
errMsg := ui.ErrorWriter.String()
if !strings.Contains(errMsg, `Unsupported Terraform Core version`) {
t.Fatal("missing version constraint error:", errMsg)
}
}
func TestZeroThirteenUpgrade_invalidFlags(t *testing.T) {
td := tempDir(t)
os.MkdirAll(td, 0755)

View File

@ -0,0 +1 @@
resource foo_instance a {}

View File

@ -0,0 +1,3 @@
terraform {
required_version = "~> 0.12.0"
}