Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make state commands check required version (#28025) #30511

Merged
merged 3 commits into from Mar 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 0 additions & 1 deletion internal/command/command_test.go
Expand Up @@ -19,7 +19,6 @@ import (
"testing"

svchost "github.com/hashicorp/terraform-svchost"

"github.com/hashicorp/terraform-svchost/disco"
"github.com/hashicorp/terraform/internal/addrs"
backendInit "github.com/hashicorp/terraform/internal/backend/init"
Expand Down
32 changes: 32 additions & 0 deletions internal/command/meta.go
Expand Up @@ -732,3 +732,35 @@ func (m *Meta) applyStateArguments(args *arguments.State) {
m.stateOutPath = args.StateOutPath
m.backupPath = args.BackupPath
}

// checkRequiredVersion loads the config and check if the
// core version requirements are satisfied.
func (m *Meta) checkRequiredVersion() tfdiags.Diagnostics {
var diags tfdiags.Diagnostics

loader, err := m.initConfigLoader()
if err != nil {
diags = diags.Append(err)
return diags
}

pwd, err := os.Getwd()
if err != nil {
diags = diags.Append(fmt.Errorf("Error getting pwd: %s", err))
return diags
}

config, configDiags := loader.LoadConfig(pwd)
if configDiags.HasErrors() {
diags = diags.Append(configDiags)
return diags
}

versionDiags := terraform.CheckCoreVersionRequirements(config)
if versionDiags.HasErrors() {
diags = diags.Append(versionDiags)
return diags
}

return nil
}
31 changes: 31 additions & 0 deletions internal/command/meta_test.go
Expand Up @@ -6,13 +6,15 @@ import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"

"github.com/google/go-cmp/cmp"

"github.com/hashicorp/terraform/internal/backend"
"github.com/hashicorp/terraform/internal/backend/local"
"github.com/hashicorp/terraform/internal/terraform"
"github.com/mitchellh/cli"
)

func TestMetaColorize(t *testing.T) {
Expand Down Expand Up @@ -386,3 +388,32 @@ func TestMeta_process(t *testing.T) {
})
}
}

func TestCommand_checkRequiredVersion(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)
testCopyDir(t, testFixturePath("command-check-required-version"), td)
defer os.RemoveAll(td)
defer testChdir(t, td)()

ui := cli.NewMockUi()
meta := Meta{
Ui: ui,
}

diags := meta.checkRequiredVersion()
if diags == nil {
t.Fatalf("diagnostics should contain unmet version constraint, but is nil")
}

meta.showDiagnostics(diags)

// Required version diags are correct
errStr := ui.ErrorWriter.String()
if !strings.Contains(errStr, `required_version = "~> 0.9.0"`) {
t.Fatalf("output should point to unmet version constraint, but is:\n\n%s", errStr)
}
if strings.Contains(errStr, `required_version = ">= 0.13.0"`) {
t.Fatalf("output should not point to met version constraint, but is:\n\n%s", errStr)
}
}
5 changes: 5 additions & 0 deletions internal/command/state_mv.go
Expand Up @@ -43,6 +43,11 @@ func (c *StateMvCommand) Run(args []string) int {
return cli.RunResultHelp
}

if diags := c.Meta.checkRequiredVersion(); diags != nil {
c.showDiagnostics(diags)
return 1
}

// If backup or backup-out options are set
// and the state option is not set, make sure
// the backend is local
Expand Down
78 changes: 78 additions & 0 deletions internal/command/state_mv_test.go
Expand Up @@ -1713,6 +1713,84 @@ func TestStateMvInvalidSourceAddress(t *testing.T) {
}
}

func TestStateMv_checkRequiredVersion(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)
testCopyDir(t, testFixturePath("command-check-required-version"), td)
defer os.RemoveAll(td)
defer testChdir(t, td)()

state := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(
addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "test_instance",
Name: "foo",
}.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance),
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"id":"bar","foo":"value","bar":"value"}`),
Status: states.ObjectReady,
},
addrs.AbsProviderConfig{
Provider: addrs.NewDefaultProvider("test"),
Module: addrs.RootModule,
},
)
s.SetResourceInstanceCurrent(
addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "test_instance",
Name: "baz",
}.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance),
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"id":"foo","foo":"value","bar":"value"}`),
Status: states.ObjectReady,
Dependencies: []addrs.ConfigResource{mustResourceAddr("test_instance.foo")},
},
addrs.AbsProviderConfig{
Provider: addrs.NewDefaultProvider("test"),
Module: addrs.RootModule,
},
)
})
statePath := testStateFile(t, state)

p := testProvider()
ui := new(cli.MockUi)
view, _ := testView(t)
c := &StateMvCommand{
StateMeta{
Meta: Meta{
testingOverrides: metaOverridesForProvider(p),
Ui: ui,
View: view,
},
},
}

args := []string{
"-state", statePath,
"test_instance.foo",
"test_instance.bar",
}

if code := c.Run(args); code != 1 {
t.Fatalf("got exit status %d; want 1\nstderr:\n%s\n\nstdout:\n%s", code, ui.ErrorWriter.String(), ui.OutputWriter.String())
}

// State is unchanged
testStateOutput(t, statePath, testStateMvOutputOriginal)

// Required version diags are correct
errStr := ui.ErrorWriter.String()
if !strings.Contains(errStr, `required_version = "~> 0.9.0"`) {
t.Fatalf("output should point to unmet version constraint, but is:\n\n%s", errStr)
}
if strings.Contains(errStr, `required_version = ">= 0.13.0"`) {
t.Fatalf("output should not point to met version constraint, but is:\n\n%s", errStr)
}
}

const testStateMvOutputOriginal = `
test_instance.baz:
ID = foo
Expand Down
5 changes: 5 additions & 0 deletions internal/command/state_pull.go
Expand Up @@ -23,6 +23,11 @@ func (c *StatePullCommand) Run(args []string) int {
return 1
}

if diags := c.Meta.checkRequiredVersion(); diags != nil {
c.showDiagnostics(diags)
return 1
}

// Load the backend
b, backendDiags := c.Backend(nil)
if backendDiags.HasErrors() {
Expand Down
32 changes: 32 additions & 0 deletions internal/command/state_pull_test.go
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"io/ioutil"
"os"
"strings"
"testing"

"github.com/mitchellh/cli"
Expand Down Expand Up @@ -64,3 +65,34 @@ func TestStatePull_noState(t *testing.T) {
t.Fatalf("bad: %s", actual)
}
}

func TestStatePull_checkRequiredVersion(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)
testCopyDir(t, testFixturePath("command-check-required-version"), td)
defer os.RemoveAll(td)
defer testChdir(t, td)()

p := testProvider()
ui := cli.NewMockUi()
c := &StatePullCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(p),
Ui: ui,
},
}

args := []string{}
if code := c.Run(args); code != 1 {
t.Fatalf("got exit status %d; want 1\nstderr:\n%s\n\nstdout:\n%s", code, ui.ErrorWriter.String(), ui.OutputWriter.String())
}

// Required version diags are correct
errStr := ui.ErrorWriter.String()
if !strings.Contains(errStr, `required_version = "~> 0.9.0"`) {
t.Fatalf("output should point to unmet version constraint, but is:\n\n%s", errStr)
}
if strings.Contains(errStr, `required_version = ">= 0.13.0"`) {
t.Fatalf("output should not point to met version constraint, but is:\n\n%s", errStr)
}
}
5 changes: 5 additions & 0 deletions internal/command/state_push.go
Expand Up @@ -38,6 +38,11 @@ func (c *StatePushCommand) Run(args []string) int {
return cli.RunResultHelp
}

if diags := c.Meta.checkRequiredVersion(); diags != nil {
c.showDiagnostics(diags)
return 1
}

// Determine our reader for the input state. This is the filepath
// or stdin if "-" is given.
var r io.Reader = os.Stdin
Expand Down
33 changes: 33 additions & 0 deletions internal/command/state_push_test.go
Expand Up @@ -291,3 +291,36 @@ func TestStatePush_forceRemoteState(t *testing.T) {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
}
}

func TestStatePush_checkRequiredVersion(t *testing.T) {
// Create a temporary working directory that is empty
td := tempDir(t)
testCopyDir(t, testFixturePath("command-check-required-version"), td)
defer os.RemoveAll(td)
defer testChdir(t, td)()

p := testProvider()
ui := cli.NewMockUi()
view, _ := testView(t)
c := &StatePushCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(p),
Ui: ui,
View: view,
},
}

args := []string{"replace.tfstate"}
if code := c.Run(args); code != 1 {
t.Fatalf("got exit status %d; want 1\nstderr:\n%s\n\nstdout:\n%s", code, ui.ErrorWriter.String(), ui.OutputWriter.String())
}

// Required version diags are correct
errStr := ui.ErrorWriter.String()
if !strings.Contains(errStr, `required_version = "~> 0.9.0"`) {
t.Fatalf("output should point to unmet version constraint, but is:\n\n%s", errStr)
}
if strings.Contains(errStr, `required_version = ">= 0.13.0"`) {
t.Fatalf("output should not point to met version constraint, but is:\n\n%s", errStr)
}
}
5 changes: 5 additions & 0 deletions internal/command/state_replace_provider.go
Expand Up @@ -42,6 +42,11 @@ func (c *StateReplaceProviderCommand) Run(args []string) int {
return cli.RunResultHelp
}

if diags := c.Meta.checkRequiredVersion(); diags != nil {
c.showDiagnostics(diags)
return 1
}

var diags tfdiags.Diagnostics

// Parse from/to arguments into providers
Expand Down