configs/configload: Don't panic when version constraint is added

Previously, adding a version constraint to a module that was previously
recorded without a version in the module manifest would cause a panic.

Instead, we now use a slight variant of the "dependencies have changed"
error that doesn't try to print out a specific version number.
This commit is contained in:
Martin Atkins 2019-06-03 08:55:43 -07:00
parent c5285021fa
commit e85093ce08
5 changed files with 55 additions and 1 deletions

View File

@ -64,7 +64,15 @@ func (l *Loader) moduleWalkerLoad(req *configs.ModuleRequest) (*configs.Module,
Subject: &req.SourceAddrRange,
})
}
if !req.VersionConstraint.Required.Check(record.Version) {
if len(req.VersionConstraint.Required) > 0 && record.Version == nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Module version requirements have changed",
Detail: "The version requirements have changed since this module was installed and the installed version is no longer acceptable. Run \"terraform init\" to install all modules required by this configuration.",
Subject: &req.SourceAddrRange,
})
}
if record.Version != nil && !req.VersionConstraint.Required.Check(record.Version) {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Module version requirements have changed",

View File

@ -58,3 +58,25 @@ func TestLoaderLoadConfig_okay(t *testing.T) {
assertResultCtyEqual(t, got, cty.StringVal("Hello from child_d"))
})
}
func TestLoaderLoadConfig_addVersion(t *testing.T) {
// This test is for what happens when there is a version constraint added
// to a module that previously didn't have one.
fixtureDir := filepath.Clean("test-fixtures/add-version-constraint")
loader, err := NewLoader(&Config{
ModulesDir: filepath.Join(fixtureDir, ".terraform/modules"),
})
if err != nil {
t.Fatalf("unexpected error from NewLoader: %s", err)
}
_, diags := loader.LoadConfig(fixtureDir)
if !diags.HasErrors() {
t.Fatalf("success; want error")
}
got := diags.Error()
want := "Module requirements have changed"
if strings.Contains(got, want) {
t.Fatalf("wrong error\ngot:\n%s\n\nwant: containing %q", got, want)
}
}

View File

@ -0,0 +1,14 @@
{
"Modules": [
{
"Key": "",
"Source": "",
"Dir": "test-fixtures/add-version-constraint"
},
{
"Key": "child",
"Source": "hashicorp/module-installer-acctest/aws",
"Dir": "test-fixtures/add-version-constraint/.terraform/modules/child"
}
]
}

View File

@ -0,0 +1,10 @@
# This fixture depends on a registry module, which indirectly refers to the
# following github repository:
#
# However, the test that uses it is testing for an error, so in practice the
# registry does not need to be accessed when this test is successful.
module "child" {
source = "hashicorp/module-installer-acctest/aws"
version = "0.0.1"
}