2023-05-02 11:33:06 -04:00
// Copyright IBM Corp. 2014, 2026
2023-08-10 18:43:27 -04:00
// SPDX-License-Identifier: BUSL-1.1
2023-05-02 11:33:06 -04:00
2014-06-19 00:36:44 -04:00
package command
import (
2014-10-01 11:43:00 -04:00
"bytes"
2021-02-02 15:38:06 -05:00
"context"
2014-07-08 00:20:48 -04:00
"fmt"
2014-07-12 00:30:40 -04:00
"io/ioutil"
2014-06-19 00:36:44 -04:00
"os"
2014-07-12 00:30:40 -04:00
"path/filepath"
2021-02-18 17:23:34 -05:00
"reflect"
2014-09-18 13:40:23 -04:00
"strings"
2014-07-08 00:20:48 -04:00
"sync"
2014-06-19 00:36:44 -04:00
"testing"
2014-07-02 20:08:58 -04:00
"time"
2014-06-19 00:36:44 -04:00
2018-10-12 19:31:18 -04:00
"github.com/google/go-cmp/cmp"
2019-06-04 10:32:12 -04:00
"github.com/google/go-cmp/cmp/cmpopts"
2023-12-20 06:04:10 -05:00
"github.com/hashicorp/cli"
2025-12-18 06:49:31 -05:00
version "github.com/hashicorp/go-version"
tfaddr "github.com/hashicorp/terraform-registry-address"
2018-05-22 22:33:45 -04:00
"github.com/zclconf/go-cty/cty"
2021-05-17 15:00:50 -04:00
"github.com/hashicorp/terraform/internal/addrs"
2024-08-26 06:43:16 -04:00
"github.com/hashicorp/terraform/internal/collections"
2021-05-17 15:17:09 -04:00
"github.com/hashicorp/terraform/internal/configs/configschema"
2021-05-17 15:33:17 -04:00
"github.com/hashicorp/terraform/internal/plans"
2021-05-17 13:40:40 -04:00
"github.com/hashicorp/terraform/internal/providers"
2024-02-16 04:35:29 -05:00
testing_provider "github.com/hashicorp/terraform/internal/providers/testing"
2021-05-17 15:43:35 -04:00
"github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/states/statemgr"
2024-10-21 08:41:58 -04:00
"github.com/hashicorp/terraform/internal/terminal"
2021-05-17 13:11:06 -04:00
"github.com/hashicorp/terraform/internal/tfdiags"
2014-06-19 00:36:44 -04:00
)
func TestApply ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-06-27 17:43:23 -04:00
statePath := testTempFile ( t )
2014-06-19 00:36:44 -04:00
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2018-05-22 22:33:45 -04:00
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-06-19 00:36:44 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-06-19 00:36:44 -04:00
}
args := [ ] string {
2014-07-12 00:30:40 -04:00
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-06-19 00:36:44 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-06-19 00:36:44 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-06-19 00:36:44 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2021-02-03 14:10:14 -05:00
func TestApply_path ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-03 14:10:14 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-03 14:10:14 -05:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2021-02-03 14:10:14 -05:00
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2021-02-03 14:10:14 -05:00
} ,
}
args := [ ] string {
"-auto-approve" ,
testFixturePath ( "apply" ) ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2021-02-03 14:10:14 -05:00
}
2021-02-18 17:23:34 -05:00
if ! strings . Contains ( output . Stderr ( ) , "-chdir" ) {
t . Fatal ( "expected command output to refer to -chdir flag, but got:" , output . Stderr ( ) )
2021-02-03 14:10:14 -05:00
}
}
2021-02-03 15:05:05 -05:00
func TestApply_approveNo ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-03 15:05:05 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-03 15:05:05 -05:00
statePath := testTempFile ( t )
2026-02-26 09:57:42 -05:00
_ = testInputMap ( t , map [ string ] string {
2021-02-18 17:23:34 -05:00
"approve" : "no" ,
2026-02-26 09:57:42 -05:00
} )
2021-02-03 15:05:05 -05:00
2021-02-18 17:23:34 -05:00
// Do not use the NewMockUi initializer here, as we want to delay
// the call to init until after setting up the input mocks
ui := new ( cli . MockUi )
2021-02-03 15:05:05 -05:00
p := applyFixtureProvider ( )
backend/local: Replace CLI with view instance
This commit extracts the remaining UI logic from the local backend,
and removes access to the direct CLI output. This is replaced with an
instance of a `views.Operation` interface, which codifies the current
requirements for the local backend to interact with the user.
The exception to this at present is interactivity: approving a plan
still depends on the `UIIn` field for the backend. This is out of scope
for this commit and can be revisited separately, at which time the
`UIOut` field can also be removed.
Changes in support of this:
- Some instances of direct error output have been replaced with
diagnostics, most notably in the emergency state backup handler. This
requires reformatting the error messages to allow the diagnostic
renderer to line-wrap them;
- The "in-automation" logic has moved out of the backend and into the
view implementation;
- The plan, apply, refresh, and import commands instantiate a view and
set it on the `backend.Operation` struct, as these are the only code
paths which call the `local.Operation()` method that requires it;
- The show command requires the plan rendering code which is now in the
views package, so there is a stub implementation of a `views.Show`
interface there.
Other refactoring work in support of migrating these commands to the
common views code structure will come in follow-up PRs, at which point
we will be able to remove the UI instances from the unit tests for those
commands.
2021-02-17 13:01:30 -05:00
view , done := testView ( t )
2021-02-03 15:05:05 -05:00
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
Ui : ui ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2021-02-03 15:05:05 -05:00
} ,
}
args := [ ] string {
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2021-02-03 15:05:05 -05:00
}
2021-02-18 17:23:34 -05:00
if got , want := output . Stdout ( ) , "Apply cancelled" ; ! strings . Contains ( got , want ) {
2021-02-03 15:05:05 -05:00
t . Fatalf ( "expected output to include %q, but was:\n%s" , want , got )
}
if _ , err := os . Stat ( statePath ) ; err == nil || ! os . IsNotExist ( err ) {
t . Fatalf ( "state file should not exist" )
}
}
func TestApply_approveYes ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-03 15:05:05 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-03 15:05:05 -05:00
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
2026-02-26 09:57:42 -05:00
_ = testInputMap ( t , map [ string ] string {
2021-02-18 17:23:34 -05:00
"approve" : "yes" ,
2026-02-26 09:57:42 -05:00
} )
2021-02-03 15:05:05 -05:00
2021-02-18 17:23:34 -05:00
// Do not use the NewMockUi initializer here, as we want to delay
// the call to init until after setting up the input mocks
2021-02-03 15:05:05 -05:00
ui := new ( cli . MockUi )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2021-02-03 15:05:05 -05:00
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
Ui : ui ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2021-02-03 15:05:05 -05:00
} ,
}
args := [ ] string {
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2021-02-03 15:05:05 -05:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
state := testStateRead ( t , statePath )
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2017-02-03 14:55:13 -05:00
// test apply with locked state
func TestApply_lockedState ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2017-02-03 14:55:13 -05:00
statePath := testTempFile ( t )
2022-04-08 12:34:16 -04:00
unlock , err := testLockState ( t , testDataDir , statePath )
2017-02-03 15:32:40 -05:00
if err != nil {
2017-02-03 14:55:13 -05:00
t . Fatal ( err )
}
2017-02-03 15:32:40 -05:00
defer unlock ( )
2017-02-03 14:55:13 -05:00
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2017-02-03 14:55:13 -05:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2017-02-03 14:55:13 -05:00
} ,
}
args := [ ] string {
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2017-02-03 14:55:13 -05:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code == 0 {
2017-02-03 15:32:40 -05:00
t . Fatal ( "expected error" )
}
2021-02-18 17:23:34 -05:00
if ! strings . Contains ( output . Stderr ( ) , "lock" ) {
t . Fatal ( "command output does not look like a lock error:" , output . Stderr ( ) )
2017-02-03 14:55:13 -05:00
}
}
2017-04-03 11:33:38 -04:00
// test apply with locked state, waiting for unlock
func TestApply_lockedStateWait ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2017-04-03 11:33:38 -04:00
statePath := testTempFile ( t )
2022-04-08 12:34:16 -04:00
unlock , err := testLockState ( t , testDataDir , statePath )
2017-04-03 11:33:38 -04:00
if err != nil {
t . Fatal ( err )
}
// unlock during apply
go func ( ) {
time . Sleep ( 500 * time . Millisecond )
unlock ( )
} ( )
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2017-04-03 11:33:38 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2017-04-03 11:33:38 -04:00
} ,
}
// wait 4s just in case the lock process doesn't release in under a second,
// and we want our context to be alive for a second retry at the 3s mark.
args := [ ] string {
"-state" , statePath ,
"-lock-timeout" , "4s" ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2017-04-03 11:33:38 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "lock should have succeeded in less than 3s: %s" , output . Stderr ( ) )
2017-04-03 11:33:38 -04:00
}
}
2021-02-02 15:38:06 -05:00
// Verify that the parallelism flag allows no more than the desired number of
// concurrent calls to ApplyResourceChange.
2015-10-14 13:43:51 -04:00
func TestApply_parallelism ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "parallelism" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2015-10-29 19:06:30 -04:00
statePath := testTempFile ( t )
2015-05-08 03:01:21 -04:00
2016-10-17 18:26:16 -04:00
par := 4
2021-02-02 15:38:06 -05:00
// started is a semaphore that we use to ensure that we never have more
// than "par" apply operations happening concurrently
started := make ( chan struct { } , par )
2016-10-17 18:26:16 -04:00
2021-02-02 15:38:06 -05:00
// beginCtx is used as a starting gate to hold back ApplyResourceChange
// calls until we reach the desired concurrency. The cancel func "begin" is
// called once we reach the desired concurrency, allowing all apply calls
// to proceed in unison.
beginCtx , begin := context . WithCancel ( context . Background ( ) )
2015-05-08 03:01:21 -04:00
2024-11-07 11:29:58 -05:00
// This just makes go vet happy, in reality the function will never exit if
// begin() isn't called inside ApplyResourceChangeFn.
defer begin ( )
2018-10-11 20:58:46 -04:00
// Since our mock provider has its own mutex preventing concurrent calls
// to ApplyResourceChange, we need to use a number of separate providers
// here. They will all have the same mock implementation function assigned
// but crucially they will each have their own mutex.
2019-12-04 11:30:20 -05:00
providerFactories := map [ addrs . Provider ] providers . Factory { }
2018-10-11 20:58:46 -04:00
for i := 0 ; i < 10 ; i ++ {
name := fmt . Sprintf ( "test%d" , i )
2024-02-16 04:35:29 -05:00
provider := & testing_provider . MockProvider { }
2021-02-18 10:13:43 -05:00
provider . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2025-03-04 10:33:43 -05:00
name + "_instance" : { Body : & configschema . Block { } } ,
2018-10-11 20:58:46 -04:00
} ,
}
2018-10-14 10:59:15 -04:00
provider . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
2018-10-11 20:58:46 -04:00
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
}
}
2018-10-14 10:59:15 -04:00
provider . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
2021-02-02 15:38:06 -05:00
// If we ever have more than our intended parallelism number of
// apply operations running concurrently, the semaphore will fail.
select {
case started <- struct { } { } :
defer func ( ) {
<- started
} ( )
default :
t . Fatal ( "too many concurrent apply operations" )
}
// If we never reach our intended parallelism, the context will
// never be canceled and the test will time out.
if len ( started ) >= par {
begin ( )
}
<- beginCtx . Done ( )
// do some "work"
// Not required for correctness, but makes it easier to spot a
// failure when there is more overlap.
time . Sleep ( 10 * time . Millisecond )
2018-10-11 20:58:46 -04:00
return providers . ApplyResourceChangeResponse {
NewState : cty . EmptyObjectVal ,
}
}
2020-04-01 15:55:25 -04:00
providerFactories [ addrs . NewDefaultProvider ( name ) ] = providers . FactoryFixed ( provider )
2018-10-11 20:58:46 -04:00
}
testingOverrides := & testingOverrides {
2020-03-30 18:30:56 -04:00
Providers : providerFactories ,
2015-05-08 03:01:21 -04:00
}
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2015-05-08 03:01:21 -04:00
c := & ApplyCommand {
Meta : Meta {
2018-10-11 20:58:46 -04:00
testingOverrides : testingOverrides ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2015-05-08 03:01:21 -04:00
} ,
}
args := [ ] string {
2015-10-29 19:06:30 -04:00
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2015-10-14 13:43:51 -04:00
fmt . Sprintf ( "-parallelism=%d" , par ) ,
2015-05-08 03:01:21 -04:00
}
2021-02-02 15:38:06 -05:00
res := c . Run ( args )
2021-02-18 17:23:34 -05:00
output := done ( t )
2021-02-02 15:38:06 -05:00
if res != 0 {
2021-02-18 17:23:34 -05:00
t . Fatal ( output . Stdout ( ) )
2015-05-08 03:01:21 -04:00
}
}
2014-07-03 00:16:36 -04:00
func TestApply_configInvalid ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-config-invalid" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-07-03 00:16:36 -04:00
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-03 00:16:36 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-07-03 00:16:36 -04:00
}
args := [ ] string {
2014-07-12 00:30:40 -04:00
"-state" , testTempFile ( t ) ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-03 00:16:36 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "bad: \n%s" , output . Stdout ( ) )
2014-07-03 00:16:36 -04:00
}
}
2014-07-12 00:30:40 -04:00
func TestApply_defaultState ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-07-12 00:30:40 -04:00
statePath := filepath . Join ( td , DefaultStateFilename )
// Change to the temporary directory
cwd , err := os . Getwd ( )
if err != nil {
t . Fatalf ( "err: %s" , err )
}
if err := os . Chdir ( filepath . Dir ( statePath ) ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
defer os . Chdir ( cwd )
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-12 00:30:40 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-07-12 00:30:40 -04:00
}
2017-07-05 18:17:07 -04:00
// create an existing state file
2020-08-11 11:43:01 -04:00
localState := statemgr . NewFilesystem ( statePath )
if err := localState . WriteState ( states . NewState ( ) ) ; err != nil {
2017-07-05 18:17:07 -04:00
t . Fatal ( err )
}
2014-07-12 00:30:40 -04:00
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-12 00:30:40 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-12 00:30:40 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-12 00:30:40 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2014-07-08 00:20:48 -04:00
func TestApply_error ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-error" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-07-08 00:20:48 -04:00
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-08 00:20:48 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-07-08 00:20:48 -04:00
}
var lock sync . Mutex
errored := false
2020-10-08 13:42:06 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) ( resp providers . ApplyResourceChangeResponse ) {
2014-07-08 00:20:48 -04:00
lock . Lock ( )
defer lock . Unlock ( )
if ! errored {
errored = true
2020-10-08 13:42:06 -04:00
resp . Diagnostics = resp . Diagnostics . Append ( fmt . Errorf ( "error" ) )
2014-07-08 00:20:48 -04:00
}
2020-10-08 13:42:06 -04:00
s := req . PlannedState . AsValueMap ( )
s [ "id" ] = cty . StringVal ( "foo" )
resp . NewState = cty . ObjectVal ( s )
return
2014-07-08 00:20:48 -04:00
}
2020-10-08 13:42:06 -04:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) ( resp providers . PlanResourceChangeResponse ) {
s := req . ProposedNewState . AsValueMap ( )
s [ "id" ] = cty . UnknownVal ( cty . String )
resp . PlannedState = cty . ObjectVal ( s )
return
2014-07-08 00:20:48 -04:00
}
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-10-12 21:04:26 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"id" : { Type : cty . String , Optional : true , Computed : true } ,
"ami" : { Type : cty . String , Optional : true } ,
"error" : { Type : cty . Bool , Optional : true } ,
} ,
2018-10-12 21:04:26 -04:00
} ,
} ,
} ,
}
2014-07-08 00:20:48 -04:00
args := [ ] string {
2014-07-12 00:30:40 -04:00
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-08 00:20:48 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "wrong exit code %d; want 1\n%s" , code , output . Stdout ( ) )
2014-07-08 00:20:48 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-08 00:20:48 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
2014-09-17 14:15:07 -04:00
if len ( state . RootModule ( ) . Resources ) == 0 {
2014-07-08 00:20:48 -04:00
t . Fatal ( "no resources in state" )
}
}
2015-01-16 13:46:38 -05:00
func TestApply_input ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-input" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2015-01-16 13:46:38 -05:00
// Disable test mode so input would be asked
test = false
defer func ( ) { test = true } ( )
2019-10-08 15:08:27 -04:00
// The configuration for this test includes a declaration of variable
// "foo" with no default, and we don't set it on the command line below,
// so the apply command will produce an interactive prompt for the
// value of var.foo. We'll answer "foo" here, and we expect the output
// value "result" to echo that back to us below.
2015-01-16 13:46:38 -05:00
defaultInputReader = bytes . NewBufferString ( "foo\n" )
defaultInputWriter = new ( bytes . Buffer )
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2015-01-16 13:46:38 -05:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2015-01-16 13:46:38 -05:00
} ,
}
args := [ ] string {
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2015-01-16 13:46:38 -05:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2015-01-16 13:46:38 -05:00
}
2018-09-29 12:35:19 -04:00
expected := strings . TrimSpace ( `
< no state >
Outputs :
result = foo
` )
testStateOutput ( t , statePath , expected )
2015-01-16 13:46:38 -05:00
}
2016-11-01 22:16:43 -04:00
// When only a partial set of the variables are set, Terraform
// should still ask for the unset ones by default (with -input=true)
func TestApply_inputPartial ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-input-partial" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2016-11-01 22:16:43 -04:00
// Disable test mode so input would be asked
test = false
defer func ( ) { test = true } ( )
// Set some default reader/writers for the inputs
defaultInputReader = bytes . NewBufferString ( "one\ntwo\n" )
defaultInputWriter = new ( bytes . Buffer )
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2016-11-01 22:16:43 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2016-11-01 22:16:43 -04:00
} ,
}
args := [ ] string {
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2016-11-01 22:16:43 -04:00
"-var" , "foo=foovalue" ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2016-11-01 22:16:43 -04:00
}
expected := strings . TrimSpace ( `
< no state >
Outputs :
bar = one
foo = foovalue
` )
testStateOutput ( t , statePath , expected )
}
2014-07-12 00:32:34 -04:00
func TestApply_noArgs ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2014-07-12 00:32:34 -04:00
statePath := testTempFile ( t )
2018-10-12 19:31:18 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-12 00:32:34 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-07-12 00:32:34 -04:00
}
args := [ ] string {
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-12 00:32:34 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-12 00:32:34 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-12 00:32:34 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2014-06-27 17:43:23 -04:00
func TestApply_plan ( t * testing . T ) {
2014-10-01 11:43:00 -04:00
// Disable test mode so input would be asked
test = false
defer func ( ) { test = true } ( )
// Set some default reader/writers for the inputs
defaultInputReader = new ( bytes . Buffer )
defaultInputWriter = new ( bytes . Buffer )
2018-10-12 21:04:26 -04:00
planPath := applyFixturePlanFile ( t )
2014-06-27 17:43:23 -04:00
statePath := testTempFile ( t )
2018-10-12 21:04:26 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-06-19 00:36:44 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-06-19 00:36:44 -04:00
}
args := [ ] string {
2017-01-18 23:50:45 -05:00
"-state-out" , statePath ,
2014-06-27 17:43:23 -04:00
planPath ,
2014-06-19 00:36:44 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-08-25 00:40:58 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-08-25 00:40:58 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2025-12-18 06:49:31 -05:00
// Test the ability to apply a plan file with a state store.
//
// The state store's details (provider, config, etc) are supplied by the plan,
// which allows this test to not use any configuration.
func TestApply_plan_stateStore ( t * testing . T ) {
// Disable test mode so input would be asked
test = false
defer func ( ) { test = true } ( )
// Set some default reader/writers for the inputs
defaultInputReader = new ( bytes . Buffer )
defaultInputWriter = new ( bytes . Buffer )
// Create the plan file that includes a state store
ver := version . Must ( version . NewVersion ( "1.2.3" ) )
providerCfg := cty . ObjectVal ( map [ string ] cty . Value {
"region" : cty . StringVal ( "spain" ) ,
} )
providerCfgRaw , err := plans . NewDynamicValue ( providerCfg , providerCfg . Type ( ) )
if err != nil {
t . Fatal ( err )
}
storeCfg := cty . ObjectVal ( map [ string ] cty . Value {
"value" : cty . StringVal ( "foobar" ) ,
} )
storeCfgRaw , err := plans . NewDynamicValue ( storeCfg , storeCfg . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plan := & plans . Plan {
Changes : plans . NewChangesSrc ( ) ,
// We'll default to the fake plan being both applyable and complete,
// since that's what most tests expect. Tests can override these
// back to false again afterwards if they need to.
Applyable : true ,
Complete : true ,
StateStore : & plans . StateStore {
Type : "test_store" ,
Provider : & plans . Provider {
Version : ver ,
Source : & tfaddr . Provider {
Hostname : tfaddr . DefaultProviderRegistryHost ,
Namespace : "hashicorp" ,
Type : "test" ,
} ,
Config : providerCfgRaw ,
} ,
Config : storeCfgRaw ,
Workspace : "default" ,
} ,
}
// Create a plan file on disk
//
// In this process we create a plan file describing the creation of a test_instance.foo resource.
state := testState ( ) // State describes
_ , snap := testModuleWithSnapshot ( t , "apply" )
planPath := testPlanFile ( t , snap , state , plan )
// Create a mock, to be used as the pluggable state store described in the planfile
mock := testStateStoreMockWithChunkNegotiation ( t , 1000 )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : & testingOverrides {
Providers : map [ addrs . Provider ] providers . Factory {
addrs . NewDefaultProvider ( "test" ) : providers . FactoryFixed ( mock ) ,
} ,
} ,
View : view ,
} ,
}
args := [ ] string {
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
}
if ! mock . WriteStateBytesCalled {
t . Fatal ( "expected the test to write new state when applying the plan, but WriteStateBytesCalled is false on the mock provider." )
}
}
// Test unhappy paths when applying a plan file describing a state store.
func TestApply_plan_stateStore_errorCases ( t * testing . T ) {
// Disable test mode so input would be asked
test = false
defer func ( ) { test = true } ( )
t . Run ( "error when the provider doesn't include the state store named in the plan" , func ( t * testing . T ) {
// Set some default reader/writers for the inputs
defaultInputReader = new ( bytes . Buffer )
defaultInputWriter = new ( bytes . Buffer )
// Create the plan file that includes a state store
ver := version . Must ( version . NewVersion ( "1.2.3" ) )
providerCfg := cty . ObjectVal ( map [ string ] cty . Value {
"region" : cty . StringVal ( "spain" ) ,
} )
providerCfgRaw , err := plans . NewDynamicValue ( providerCfg , providerCfg . Type ( ) )
if err != nil {
t . Fatal ( err )
}
storeCfg := cty . ObjectVal ( map [ string ] cty . Value {
"value" : cty . StringVal ( "foobar" ) ,
} )
storeCfgRaw , err := plans . NewDynamicValue ( storeCfg , storeCfg . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plan := & plans . Plan {
Changes : plans . NewChangesSrc ( ) ,
// We'll default to the fake plan being both applyable and complete,
// since that's what most tests expect. Tests can override these
// back to false again afterwards if they need to.
Applyable : true ,
Complete : true ,
StateStore : & plans . StateStore {
Type : "test_doesnt_exist" , // Mismatched with test_store in the provider
Provider : & plans . Provider {
Version : ver ,
Source : & tfaddr . Provider {
Hostname : tfaddr . DefaultProviderRegistryHost ,
Namespace : "hashicorp" ,
Type : "test" ,
} ,
Config : providerCfgRaw ,
} ,
Config : storeCfgRaw ,
Workspace : "default" ,
} ,
}
// Create a plan file on disk
//
// In this process we create a plan file describing the creation of a test_instance.foo resource.
state := testState ( ) // State describes
_ , snap := testModuleWithSnapshot ( t , "apply" )
planPath := testPlanFile ( t , snap , state , plan )
// Create a mock, to be used as the pluggable state store described in the planfile
mock := testStateStoreMockWithChunkNegotiation ( t , 1000 )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : & testingOverrides {
Providers : map [ addrs . Provider ] providers . Factory {
addrs . NewDefaultProvider ( "test" ) : providers . FactoryFixed ( mock ) ,
} ,
} ,
View : view ,
} ,
}
args := [ ] string {
planPath ,
"-no-color" ,
}
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "expected an error but got none: %d\n\n%s" , code , output . Stdout ( ) )
}
expectedErr := "Error: State store not implemented by the provider"
if ! strings . Contains ( output . Stderr ( ) , expectedErr ) {
t . Fatalf ( "expected error to include %q, but got:\n%s" , expectedErr , output . Stderr ( ) )
}
} )
t . Run ( "error when the provider doesn't implement state stores" , func ( t * testing . T ) {
// Set some default reader/writers for the inputs
defaultInputReader = new ( bytes . Buffer )
defaultInputWriter = new ( bytes . Buffer )
// Create the plan file that includes a state store
ver := version . Must ( version . NewVersion ( "1.2.3" ) )
providerCfg := cty . ObjectVal ( map [ string ] cty . Value {
"region" : cty . StringVal ( "spain" ) ,
} )
providerCfgRaw , err := plans . NewDynamicValue ( providerCfg , providerCfg . Type ( ) )
if err != nil {
t . Fatal ( err )
}
storeCfg := cty . ObjectVal ( map [ string ] cty . Value {
"value" : cty . StringVal ( "foobar" ) ,
} )
storeCfgRaw , err := plans . NewDynamicValue ( storeCfg , storeCfg . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plan := & plans . Plan {
Changes : plans . NewChangesSrc ( ) ,
// We'll default to the fake plan being both applyable and complete,
// since that's what most tests expect. Tests can override these
// back to false again afterwards if they need to.
Applyable : true ,
Complete : true ,
StateStore : & plans . StateStore {
Type : "test_store" ,
Provider : & plans . Provider {
Version : ver ,
Source : & tfaddr . Provider {
Hostname : tfaddr . DefaultProviderRegistryHost ,
Namespace : "hashicorp" ,
Type : "test" ,
} ,
Config : providerCfgRaw ,
} ,
Config : storeCfgRaw ,
Workspace : "default" ,
} ,
}
// Create a plan file on disk
//
// In this process we create a plan file describing the creation of a test_instance.foo resource.
state := testState ( ) // State describes
_ , snap := testModuleWithSnapshot ( t , "apply" )
planPath := testPlanFile ( t , snap , state , plan )
// Create a mock, to be used as the pluggable state store described in the planfile
mock := & testing_provider . MockProvider { }
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : & testingOverrides {
Providers : map [ addrs . Provider ] providers . Factory {
addrs . NewDefaultProvider ( "test" ) : providers . FactoryFixed ( mock ) ,
} ,
} ,
View : view ,
} ,
}
args := [ ] string {
planPath ,
"-no-color" ,
}
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "expected an error but got none: %d\n\n%s" , code , output . Stdout ( ) )
}
expectedErr := "Error: Provider does not support pluggable state storage"
if ! strings . Contains ( output . Stderr ( ) , expectedErr ) {
t . Fatalf ( "expected error to include %q, but got:\n%s" , expectedErr , output . Stderr ( ) )
}
} )
}
2016-10-28 20:51:05 -04:00
func TestApply_plan_backup ( t * testing . T ) {
statePath := testTempFile ( t )
backupPath := testTempFile ( t )
2018-10-12 21:04:26 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2016-10-28 20:51:05 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2016-10-28 20:51:05 -04:00
} ,
}
2017-02-03 13:07:34 -05:00
// create a state file that needs to be backed up
2021-10-13 17:28:14 -04:00
fs := statemgr . NewFilesystem ( statePath )
fs . StateSnapshotMeta ( )
err := fs . WriteState ( states . NewState ( ) )
2017-02-03 13:07:34 -05:00
if err != nil {
t . Fatal ( err )
}
2018-10-16 20:51:47 -04:00
2021-10-13 17:28:14 -04:00
// the plan file must contain the metadata from the prior state to be
// backed up
planPath := applyFixturePlanFileMatchState ( t , fs . StateSnapshotMeta ( ) )
2017-03-13 19:41:33 -04:00
args := [ ] string {
2018-10-16 20:51:47 -04:00
"-state" , statePath ,
2016-10-28 20:51:05 -04:00
"-backup" , backupPath ,
planPath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2016-10-28 20:51:05 -04:00
}
2017-07-05 18:17:07 -04:00
// Should have a backup file
testStateRead ( t , backupPath )
2016-10-28 20:51:05 -04:00
}
func TestApply_plan_noBackup ( t * testing . T ) {
2018-10-12 21:04:26 -04:00
planPath := applyFixturePlanFile ( t )
2016-10-28 20:51:05 -04:00
statePath := testTempFile ( t )
2018-10-12 21:04:26 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2016-10-28 20:51:05 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2016-10-28 20:51:05 -04:00
} ,
}
args := [ ] string {
2017-01-18 23:50:45 -05:00
"-state-out" , statePath ,
2016-10-28 20:51:05 -04:00
"-backup" , "-" ,
planPath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2016-10-28 20:51:05 -04:00
}
// Ensure there is no backup
_ , err := os . Stat ( statePath + DefaultBackupExtension )
if err == nil || ! os . IsNotExist ( err ) {
t . Fatalf ( "backup should not exist" )
}
// Ensure there is no literal "-"
_ , err = os . Stat ( "-" )
if err == nil || ! os . IsNotExist ( err ) {
t . Fatalf ( "backup should not exist" )
}
}
2015-01-07 16:08:32 -05:00
func TestApply_plan_remoteState ( t * testing . T ) {
// Disable test mode so input would be asked
test = false
defer func ( ) { test = true } ( )
2025-07-16 06:41:51 -04:00
tmp := t . TempDir ( )
t . Chdir ( tmp )
2015-02-22 14:13:21 -05:00
remoteStatePath := filepath . Join ( tmp , DefaultDataDir , DefaultStateFilename )
if err := os . MkdirAll ( filepath . Dir ( remoteStatePath ) , 0755 ) ; err != nil {
t . Fatalf ( "err: %s" , err )
2015-01-07 16:08:32 -05:00
}
// Set some default reader/writers for the inputs
defaultInputReader = new ( bytes . Buffer )
defaultInputWriter = new ( bytes . Buffer )
// Create a remote state
state := testState ( )
2018-11-08 18:22:41 -05:00
_ , srv := testRemoteState ( t , state , 200 )
2015-01-07 16:08:32 -05:00
defer srv . Close ( )
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
_ , snap := testModuleWithSnapshot ( t , "apply" )
2018-10-12 21:04:26 -04:00
backendConfig := cty . ObjectVal ( map [ string ] cty . Value {
2023-01-26 09:08:07 -05:00
"address" : cty . StringVal ( srv . URL ) ,
"update_method" : cty . NullVal ( cty . String ) ,
"lock_address" : cty . NullVal ( cty . String ) ,
"unlock_address" : cty . NullVal ( cty . String ) ,
"lock_method" : cty . NullVal ( cty . String ) ,
"unlock_method" : cty . NullVal ( cty . String ) ,
"username" : cty . NullVal ( cty . String ) ,
"password" : cty . NullVal ( cty . String ) ,
"skip_cert_verification" : cty . NullVal ( cty . Bool ) ,
"retry_max" : cty . NullVal ( cty . String ) ,
"retry_wait_min" : cty . NullVal ( cty . String ) ,
"retry_wait_max" : cty . NullVal ( cty . String ) ,
"client_ca_certificate_pem" : cty . NullVal ( cty . String ) ,
"client_certificate_pem" : cty . NullVal ( cty . String ) ,
"client_private_key_pem" : cty . NullVal ( cty . String ) ,
2018-10-12 21:04:26 -04:00
} )
backendConfigRaw , err := plans . NewDynamicValue ( backendConfig , backendConfig . Type ( ) )
if err != nil {
t . Fatal ( err )
}
planPath := testPlanFile ( t , snap , state , & plans . Plan {
2025-11-28 11:12:46 -05:00
Backend : & plans . Backend {
2026-02-03 10:29:58 -05:00
Type : "http" ,
Config : backendConfigRaw ,
Workspace : "default" ,
2018-10-12 21:04:26 -04:00
} ,
2024-08-12 14:28:26 -04:00
Changes : plans . NewChangesSrc ( ) ,
2018-10-12 21:04:26 -04:00
} )
2015-01-07 16:08:32 -05:00
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2015-01-07 16:08:32 -05:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2015-01-07 16:08:32 -05:00
} ,
}
args := [ ] string {
planPath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2015-01-07 16:08:32 -05:00
}
// State file should be not be installed
2015-02-22 14:13:21 -05:00
if _ , err := os . Stat ( filepath . Join ( tmp , DefaultStateFilename ) ) ; err == nil {
2017-01-18 23:50:45 -05:00
data , _ := ioutil . ReadFile ( DefaultStateFilename )
t . Fatalf ( "State path should not exist: %s" , string ( data ) )
2015-01-07 16:08:32 -05:00
}
2017-01-18 23:50:45 -05:00
// Check that there is no remote state config
2018-11-08 18:22:41 -05:00
if src , err := ioutil . ReadFile ( remoteStatePath ) ; err == nil {
t . Fatalf ( "has %s file; should not\n%s" , remoteStatePath , src )
2015-01-07 16:08:32 -05:00
}
}
2014-08-25 00:40:58 -04:00
func TestApply_planWithVarFile ( t * testing . T ) {
varFileDir := testTempDir ( t )
varFilePath := filepath . Join ( varFileDir , "terraform.tfvars" )
2024-11-18 10:17:18 -05:00
if err := os . WriteFile ( varFilePath , [ ] byte ( applyVarFile ) , 0644 ) ; err != nil {
2014-08-25 00:40:58 -04:00
t . Fatalf ( "err: %s" , err )
}
2024-11-04 09:34:14 -05:00
// The value of foo is the same as in the var file
2024-11-04 08:32:15 -05:00
planPath := applyFixturePlanFileWithVariableValue ( t , "bar" )
2014-08-25 00:40:58 -04:00
statePath := testTempFile ( t )
cwd , err := os . Getwd ( )
if err != nil {
t . Fatalf ( "err: %s" , err )
}
if err := os . Chdir ( varFileDir ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
defer os . Chdir ( cwd )
2018-10-12 21:04:26 -04:00
p := applyFixtureProvider ( )
2024-11-18 10:17:18 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
ResourceTypes : map [ string ] providers . Schema {
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2024-11-18 10:17:18 -05:00
Attributes : map [ string ] * configschema . Attribute {
"id" : { Type : cty . String , Computed : true } ,
"value" : { Type : cty . String , Optional : true } ,
} ,
} ,
} ,
} ,
}
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-08-25 00:40:58 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-08-25 00:40:58 -04:00
} ,
}
args := [ ] string {
2017-01-18 23:50:45 -05:00
"-state-out" , statePath ,
2014-08-25 00:40:58 -04:00
planPath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-06-19 00:36:44 -04:00
}
2014-06-27 17:43:23 -04:00
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-06-27 17:43:23 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2024-11-04 09:34:14 -05:00
func TestApply_planWithVarFileChangingVariableValue ( t * testing . T ) {
varFileDir := testTempDir ( t )
2024-12-09 12:13:08 -05:00
varFilePath := filepath . Join ( varFileDir , "terraform-test.tfvars" )
2024-11-17 12:45:41 -05:00
if err := os . WriteFile ( varFilePath , [ ] byte ( applyVarFile ) , 0644 ) ; err != nil {
2024-11-04 09:34:14 -05:00
t . Fatalf ( "err: %s" , err )
}
2024-11-17 12:45:41 -05:00
// The value of foo is different from the var file
2024-11-04 09:34:14 -05:00
planPath := applyFixturePlanFileWithVariableValue ( t , "lorem ipsum" )
statePath := testTempFile ( t )
cwd , err := os . Getwd ( )
if err != nil {
t . Fatalf ( "err: %s" , err )
}
if err := os . Chdir ( varFileDir ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
defer os . Chdir ( cwd )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-state-out" , statePath ,
2024-12-09 12:13:08 -05:00
"-var-file" , varFilePath ,
2024-11-04 09:34:14 -05:00
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code == 0 {
t . Fatalf ( "expected to fail, but succeeded. \n\n%s" , output . All ( ) )
}
expectedTitle := "Can't change variable when applying a saved plan"
if ! strings . Contains ( output . Stderr ( ) , expectedTitle ) {
t . Fatalf ( "Expected stderr to contain %q, got %q" , expectedTitle , output . Stderr ( ) )
}
}
2024-11-27 13:00:53 -05:00
func TestApply_planUndeclaredVars ( t * testing . T ) {
// This test ensures that it isn't allowed to set undeclared input variables
// when applying from a saved plan file, since in that case the variable
// values come from the saved plan file.
2024-05-07 19:33:35 -04:00
2018-10-12 21:04:26 -04:00
planPath := applyFixturePlanFile ( t )
2014-07-26 17:32:09 -04:00
statePath := testTempFile ( t )
2018-10-12 21:04:26 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-26 17:32:09 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-26 17:32:09 -04:00
} ,
}
args := [ ] string {
"-state" , statePath ,
"-var" , "foo=bar" ,
planPath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code == 0 {
t . Fatal ( "should've failed: " , output . Stdout ( ) )
2014-07-26 17:32:09 -04:00
}
}
2025-02-05 12:27:15 -05:00
func TestApply_planWithEnvVars ( t * testing . T ) {
_ , snap := testModuleWithSnapshot ( t , "apply-output-only" )
plan := testPlan ( t )
addr , diags := addrs . ParseAbsOutputValueStr ( "output.shadow" )
if diags . HasErrors ( ) {
t . Fatal ( diags . Err ( ) )
}
shadowVal := mustNewDynamicValue ( "noot" , cty . DynamicPseudoType )
plan . VariableValues = map [ string ] plans . DynamicValue {
"shadow" : shadowVal ,
}
plan . Changes . Outputs = append ( plan . Changes . Outputs , & plans . OutputChangeSrc {
Addr : addr ,
ChangeSrc : plans . ChangeSrc {
Action : plans . Create ,
After : shadowVal ,
} ,
} )
planPath := testPlanFileMatchState (
t ,
snap ,
states . NewState ( ) ,
plan ,
statemgr . SnapshotMeta { } ,
)
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
t . Setenv ( "TF_VAR_shadow" , "env" )
args := [ ] string {
"-state" , statePath ,
"-no-color" ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatal ( "unexpected failure: " , output . All ( ) )
}
expectedWarn := "Warning: Ignoring variable when applying a saved plan\n"
if ! strings . Contains ( output . Stdout ( ) , expectedWarn ) {
t . Fatalf ( "expected warning in output, given: %q" , output . Stdout ( ) )
}
}
2025-09-10 05:11:31 -04:00
func TestApply_planWithSensitiveEnvVars ( t * testing . T ) {
_ , snap := testModuleWithSnapshot ( t , "apply-sensitive-variable" )
plan := testPlan ( t )
addr , diags := addrs . ParseAbsOutputValueStr ( "output.shadow" )
if diags . HasErrors ( ) {
t . Fatal ( diags . Err ( ) )
}
shadowVal := mustNewDynamicValue ( "noot" , cty . DynamicPseudoType )
plan . VariableValues = map [ string ] plans . DynamicValue {
"shadow" : shadowVal ,
}
plan . Changes . Outputs = append ( plan . Changes . Outputs , & plans . OutputChangeSrc {
Addr : addr ,
ChangeSrc : plans . ChangeSrc {
Action : plans . Create ,
After : shadowVal ,
} ,
} )
planPath := testPlanFileMatchState (
t ,
snap ,
states . NewState ( ) ,
plan ,
statemgr . SnapshotMeta { } ,
)
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
t . Setenv ( "TF_VAR_shadow" , "unique" )
args := [ ] string {
"-state" , statePath ,
"-no-color" ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatal ( "unexpected failure: " , output . All ( ) )
}
out := output . Stdout ( )
expectedWarn := "Warning: Ignoring variable when applying a saved plan\n"
if ! strings . Contains ( out , expectedWarn ) {
t . Fatalf ( "expected warning in output, given: %q" , out )
}
if ! strings . Contains ( out , "(sensitive value)" ) {
t . Error ( "should have elided sensitive value" )
}
if strings . Contains ( out , "noot" ) {
t . Error ( "should have elided sensitive input, but contained value" )
}
if strings . Contains ( out , "unique" ) {
t . Error ( "should have elided sensitive input, but contained value" )
}
}
2024-08-26 06:43:16 -04:00
// A saved plan includes a list of "apply-time variables", i.e. ephemeral
// input variables that were set during the plan, and must therefore be set
// during apply. No other variables may be set during apply.
//
// Test that an apply supplying all apply-time variables succeeds, and then test
// that supplying a declared ephemeral input variable that is *not* in the list
// of apply-time variables fails.
2024-11-06 08:20:02 -05:00
//
// In the fixture used for this test foo is a required ephemeral variable, whereas bar is
// an optional one.
2024-08-26 06:43:16 -04:00
func TestApply_planVarsEphemeral_applyTime ( t * testing . T ) {
2024-10-24 10:17:44 -04:00
for name , tc := range map [ string ] func ( * testing . T , * ApplyCommand , string , string , func ( * testing . T ) * terminal . TestOutput ) {
2024-11-06 08:20:02 -05:00
"with planfile only passing ephemeral variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
2024-10-24 10:17:44 -04:00
args := [ ] string {
"-state" , statePath ,
"-var" , "foo=bar" ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
2024-11-06 08:20:02 -05:00
t . Fatal ( "should've succeeded: " , output . All ( ) )
2024-10-24 10:17:44 -04:00
}
2024-08-26 06:43:16 -04:00
} ,
2024-11-06 08:20:02 -05:00
"with planfile passing non-ephemeral variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
2024-10-24 10:17:44 -04:00
args := [ ] string {
"-state" , statePath ,
"-var" , "foo=bar" ,
"-var" , "bar=bar" ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code == 0 {
2024-11-06 08:20:02 -05:00
t . Fatal ( "should've failed: " , output . All ( ) )
2024-10-24 10:17:44 -04:00
}
} ,
2024-08-26 06:43:16 -04:00
2024-11-06 08:20:02 -05:00
"with planfile missing ephemeral variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
2024-10-24 10:17:44 -04:00
args := [ ] string {
"-state" , statePath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code == 0 {
2024-11-06 08:20:02 -05:00
t . Fatal ( "should've failed: " , output . All ( ) )
2024-10-24 10:17:44 -04:00
}
} ,
2024-10-21 08:41:58 -04:00
2024-11-06 08:20:02 -05:00
"with planfile passing ephemeral variable through vars file" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
2024-10-24 10:17:44 -04:00
const planVarFile = `
foo = "bar"
`
2024-08-26 06:43:16 -04:00
2024-10-24 10:17:44 -04:00
// Write a tfvars file with the variable
tfVarsPath := testVarsFile ( t )
err := os . WriteFile ( tfVarsPath , [ ] byte ( planVarFile ) , 0600 )
if err != nil {
t . Fatalf ( "Could not write vars file %e" , err )
}
2024-08-26 06:43:16 -04:00
2024-10-24 10:17:44 -04:00
args := [ ] string {
"-state" , statePath ,
"-var-file" , tfVarsPath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
2024-11-06 08:20:02 -05:00
t . Fatal ( "should've succeeded: " , output . All ( ) )
2024-10-24 10:17:44 -04:00
}
} ,
2024-10-23 06:37:04 -04:00
2024-11-06 08:20:02 -05:00
"with planfile passing ephemeral variable through environment variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
2024-10-24 10:17:44 -04:00
t . Setenv ( "TF_VAR_foo" , "bar" )
2024-10-23 06:37:04 -04:00
2024-10-24 10:17:44 -04:00
args := [ ] string {
"-state" , statePath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
2024-11-06 08:20:02 -05:00
t . Fatal ( "should've succeeded: " , output . All ( ) )
}
} ,
"with planfile passing ephemeral variable through interactive prompts" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
close := testInteractiveInput ( t , [ ] string { "bar" } )
defer close ( )
args := [ ] string {
"-state" , statePath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code == 0 {
// We don't support interactive inputs for apply-time variables
t . Fatal ( "should have failed: " , output . All ( ) )
}
} ,
"without planfile only passing ephemeral variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
args := [ ] string {
"-state" , statePath ,
"-var" , "foo=bar" ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatal ( "should've succeeded: " , output . All ( ) )
}
} ,
"without planfile passing non-ephemeral variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
args := [ ] string {
"-state" , statePath ,
"-var" , "foo=bar" ,
"-var" , "bar=bar" ,
}
code := c . Run ( args )
output := done ( t )
// For a combined plan & apply operation it's okay (and expected) to also be able to pass non-ephemeral variables
if code != 0 {
t . Fatal ( "should've succeeded: " , output . All ( ) )
}
} ,
"without planfile missing ephemeral variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
args := [ ] string {
"-state" , statePath ,
}
code := c . Run ( args )
output := done ( t )
if code == 0 {
t . Fatal ( "should've failed: " , output . All ( ) )
}
} ,
"without planfile passing ephemeral variable through vars file" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
const planVarFile = `
foo = "bar"
`
// Write a tfvars file with the variable
tfVarsPath := testVarsFile ( t )
err := os . WriteFile ( tfVarsPath , [ ] byte ( planVarFile ) , 0600 )
if err != nil {
t . Fatalf ( "Could not write vars file %e" , err )
}
args := [ ] string {
"-state" , statePath ,
"-var-file" , tfVarsPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatal ( "should've succeeded: " , output . All ( ) )
2024-10-24 10:17:44 -04:00
}
} ,
2024-10-23 06:37:04 -04:00
2024-11-06 08:20:02 -05:00
"without planfile passing ephemeral variable through environment variable" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
t . Setenv ( "TF_VAR_foo" , "bar" )
2024-11-27 13:00:53 -05:00
t . Setenv ( "TF_VAR_unused" , ` { key:"val"} ` )
2024-11-06 08:20:02 -05:00
args := [ ] string {
"-state" , statePath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatal ( "should've succeeded: " , output . All ( ) )
}
} ,
"without planfile passing ephemeral variable through interactive prompts" : func ( t * testing . T , c * ApplyCommand , statePath , planPath string , done func ( * testing . T ) * terminal . TestOutput ) {
close := testInteractiveInput ( t , [ ] string { "bar" } )
defer close ( )
args := [ ] string {
"-state" , statePath ,
}
code := c . Run ( args )
output := done ( t )
2024-11-07 05:48:55 -05:00
if code != 0 {
t . Fatal ( "should've succeeded: " , output . All ( ) )
2024-11-06 08:20:02 -05:00
}
} ,
2024-10-24 10:17:44 -04:00
} {
t . Run ( name , func ( t * testing . T ) {
td := t . TempDir ( )
testCopyDir ( t , testFixturePath ( "apply-ephemeral-variable" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2024-10-24 10:17:44 -04:00
_ , snap := testModuleWithSnapshot ( t , "apply-ephemeral-variable" )
plannedVal := cty . ObjectVal ( map [ string ] cty . Value {
"id" : cty . UnknownVal ( cty . String ) ,
"ami" : cty . StringVal ( "bar" ) ,
} )
priorValRaw , err := plans . NewDynamicValue ( cty . NullVal ( plannedVal . Type ( ) ) , plannedVal . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plannedValRaw , err := plans . NewDynamicValue ( plannedVal , plannedVal . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plan := testPlan ( t )
plan . Changes . AppendResourceInstanceChange ( & plans . ResourceInstanceChangeSrc {
Addr : addrs . Resource {
Mode : addrs . ManagedResourceMode ,
Type : "test_instance" ,
Name : "foo" ,
} . Instance ( addrs . NoKey ) . Absolute ( addrs . RootModuleInstance ) ,
ProviderAddr : addrs . AbsProviderConfig {
Provider : addrs . NewDefaultProvider ( "test" ) ,
Module : addrs . RootModule ,
} ,
ChangeSrc : plans . ChangeSrc {
Action : plans . Create ,
Before : priorValRaw ,
After : plannedValRaw ,
} ,
} )
applyTimeVariables := collections . NewSetCmp [ string ] ( )
applyTimeVariables . Add ( "foo" )
plan . ApplyTimeVariables = applyTimeVariables
planPath := testPlanFileMatchState (
t ,
snap ,
states . NewState ( ) ,
plan ,
statemgr . SnapshotMeta { } ,
)
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
2024-10-23 06:37:04 -04:00
2024-10-24 10:17:44 -04:00
tc ( t , c , statePath , planPath , done )
} )
}
2024-08-26 06:43:16 -04:00
}
2024-11-17 12:45:41 -05:00
// Variables can be passed to apply now for ephemeral usage, but we need to
// ensure that the legacy handling of undeclared variables remains intact
func TestApply_changedVars_applyTime ( t * testing . T ) {
t . Run ( "undeclared-config-var" , func ( t * testing . T ) {
// an undeclared config variable is a warning, just like during plan
varFileDir := testTempDir ( t )
varFilePath := filepath . Join ( varFileDir , "terraform.tfvars" )
if err := os . WriteFile ( varFilePath , [ ] byte ( ` undeclared = true ` ) , 0644 ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
// The value of foo is not set
planPath := applyFixturePlanFile ( t )
statePath := testTempFile ( t )
cwd , err := os . Getwd ( )
if err != nil {
t . Fatalf ( "err: %s" , err )
}
if err := os . Chdir ( varFileDir ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
defer os . Chdir ( cwd )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-state-out" , statePath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "unexpected exit code %d:\n\n%s" , code , output . All ( ) )
}
if ! strings . Contains ( output . All ( ) , ` Value for undeclared variable ` ) {
t . Fatalf ( "missing undeclared warning:\n%s" , output . All ( ) )
}
} )
t . Run ( "undeclared-cli-var" , func ( t * testing . T ) {
// an undeclared cli variable is an error, just like during plan
planPath := applyFixturePlanFile ( t )
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-var" , "undeclared=true" ,
"-state-out" , statePath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "unexpected exit code %d:\n\n%s" , code , output . All ( ) )
}
if ! strings . Contains ( output . Stderr ( ) , ` Value for undeclared variable ` ) {
t . Fatalf ( "missing undeclared warning:\n%s" , output . All ( ) )
}
} )
t . Run ( "changed-cli-var" , func ( t * testing . T ) {
planPath := applyFixturePlanFileWithVariableValue ( t , "orig" )
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-var" , "foo=new" ,
"-state-out" , statePath ,
planPath ,
}
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "unexpected exit code %d:\n\n%s" , code , output . All ( ) )
}
if ! strings . Contains ( output . Stderr ( ) , ` Can't change variable when applying a saved plan ` ) {
t . Fatalf ( "missing undeclared warning:\n%s" , output . All ( ) )
}
} )
2024-12-09 12:13:08 -05:00
t . Run ( "var-file-override-auto" , func ( t * testing . T ) {
// for this one we're going to do a full plan to make sure the variables
// can be applied consistently. The plan specifies a var file, and
// during apply we don't want to override that with the default or auto
// var files.
td := t . TempDir ( )
testCopyDir ( t , testFixturePath ( "apply-vars-auto" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2024-12-09 12:13:08 -05:00
p := planVarsFixtureProvider ( )
view , done := testView ( t )
c := & PlanCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-var-file" , "terraform-test.tfvars" ,
"-out" , "planfile" ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "non-zero exit %d\n\n%s" , code , output . Stderr ( ) )
}
view , done = testView ( t )
apply := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
Ui : new ( cli . MockUi ) ,
View : view ,
} ,
}
args = [ ] string {
"planfile" ,
}
code = apply . Run ( args )
output = done ( t )
if code != 0 {
t . Fatalf ( "non-zero exit %d\n\n%s" , code , output . Stderr ( ) )
}
} )
2024-11-17 12:45:41 -05:00
}
2017-03-27 18:39:18 -04:00
// we should be able to apply a plan file with no other file dependencies
func TestApply_planNoModuleFiles ( t * testing . T ) {
2017-04-26 10:10:04 -04:00
// temporary data directory which we can remove between commands
2018-03-28 13:08:38 -04:00
td := testTempDir ( t )
2017-03-27 18:39:18 -04:00
defer os . RemoveAll ( td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2017-03-27 18:39:18 -04:00
2018-10-12 21:04:26 -04:00
p := applyFixtureProvider ( )
planPath := applyFixturePlanFile ( t )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2017-03-27 18:39:18 -04:00
apply := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
Ui : new ( cli . MockUi ) ,
2021-02-11 20:52:10 -05:00
View : view ,
2017-03-27 18:39:18 -04:00
} ,
}
args := [ ] string {
2018-10-12 21:04:26 -04:00
planPath ,
2017-03-27 18:39:18 -04:00
}
apply . Run ( args )
2021-02-18 17:23:34 -05:00
done ( t )
2017-03-27 18:39:18 -04:00
}
2014-07-26 20:50:13 -04:00
func TestApply_refresh ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
originalState := 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 {
2018-10-12 19:31:18 -04:00
AttrsJSON : [ ] byte ( ` { "ami":"bar"} ` ) ,
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
Status : states . ObjectReady ,
2014-07-26 20:50:13 -04:00
} ,
2020-02-13 15:32:58 -05:00
addrs . AbsProviderConfig {
2020-04-01 15:55:25 -04:00
Provider : addrs . NewDefaultProvider ( "test" ) ,
2020-03-11 14:19:52 -04:00
Module : addrs . RootModule ,
2020-02-13 15:32:58 -05:00
} ,
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
)
} )
2014-07-26 20:50:13 -04:00
statePath := testStateFile ( t , originalState )
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-26 20:50:13 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-26 20:50:13 -04:00
} ,
}
args := [ ] string {
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-26 20:50:13 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-26 20:50:13 -04:00
}
2018-09-29 12:35:19 -04:00
if ! p . ReadResourceCalled {
t . Fatal ( "should call ReadResource" )
2014-07-26 20:50:13 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-26 20:50:13 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
2014-07-27 23:38:41 -04:00
// Should have a backup file
2017-07-05 17:59:42 -04:00
backupState := testStateRead ( t , statePath + DefaultBackupExtension )
2014-07-27 23:38:41 -04:00
2014-09-18 20:16:09 -04:00
actualStr := strings . TrimSpace ( backupState . String ( ) )
expectedStr := strings . TrimSpace ( originalState . String ( ) )
if actualStr != expectedStr {
t . Fatalf ( "bad:\n\n%s\n\n%s" , actualStr , expectedStr )
2014-07-27 23:38:41 -04:00
}
2014-07-26 20:50:13 -04:00
}
2021-05-05 14:13:20 -04:00
func TestApply_refreshFalse ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-05-05 14:13:20 -04:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-05-05 14:13:20 -04:00
originalState := 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 ( ` { "ami":"bar"} ` ) ,
Status : states . ObjectReady ,
} ,
addrs . AbsProviderConfig {
Provider : addrs . NewDefaultProvider ( "test" ) ,
Module : addrs . RootModule ,
} ,
)
} )
statePath := testStateFile ( t , originalState )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-state" , statePath ,
"-auto-approve" ,
"-refresh=false" ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
}
if p . ReadResourceCalled {
t . Fatal ( "should not call ReadResource when refresh=false" )
}
}
2026-02-26 09:57:42 -05:00
2014-07-02 20:01:02 -04:00
func TestApply_shutdown ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-shutdown" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2018-02-09 19:13:34 -05:00
cancelled := make ( chan struct { } )
shutdownCh := make ( chan struct { } )
2014-07-02 20:01:02 -04:00
statePath := testTempFile ( t )
p := testProvider ( )
2017-12-01 11:27:32 -05:00
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-02 20:01:02 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2017-12-01 11:03:41 -05:00
ShutdownCh : shutdownCh ,
2014-07-12 23:37:30 -04:00
} ,
2014-07-02 20:01:02 -04:00
}
2017-12-02 22:36:43 -05:00
p . StopFn = func ( ) error {
2018-02-09 19:13:34 -05:00
close ( cancelled )
2017-12-02 22:36:43 -05:00
return nil
}
2020-10-08 13:42:06 -04:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) ( resp providers . PlanResourceChangeResponse ) {
resp . PlannedState = req . ProposedNewState
return
2014-07-02 20:01:02 -04:00
}
2018-02-09 19:13:34 -05:00
var once sync . Once
2020-10-08 13:42:06 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) ( resp providers . ApplyResourceChangeResponse ) {
2017-12-02 22:36:43 -05:00
// only cancel once
2018-02-09 19:13:34 -05:00
once . Do ( func ( ) {
2017-12-01 11:27:32 -05:00
shutdownCh <- struct { } { }
2018-02-09 19:13:34 -05:00
} )
// Because of the internal lock in the MockProvider, we can't
// coordiante directly with the calling of Stop, and making the
// MockProvider concurrent is disruptive to a lot of existing tests.
// Wait here a moment to help make sure the main goroutine gets to the
// Stop call before we exit, or the plan may finish before it can be
// canceled.
time . Sleep ( 200 * time . Millisecond )
2020-10-08 13:42:06 -04:00
resp . NewState = req . PlannedState
return
2014-07-02 20:01:02 -04:00
}
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-10-12 19:31:18 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"ami" : { Type : cty . String , Optional : true } ,
} ,
2018-10-12 19:31:18 -04:00
} ,
} ,
} ,
}
2014-07-02 20:01:02 -04:00
args := [ ] string {
2014-07-12 00:30:40 -04:00
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-02 20:01:02 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-02 20:01:02 -04:00
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2018-02-09 19:13:34 -05:00
select {
case <- cancelled :
default :
2017-12-01 11:27:32 -05:00
t . Fatal ( "command not cancelled" )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-02 20:01:02 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
}
2014-06-27 17:43:23 -04:00
func TestApply_state ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
originalState := 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 {
2018-10-16 20:51:47 -04:00
AttrsJSON : [ ] byte ( ` { "ami":"foo"} ` ) ,
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
Status : states . ObjectReady ,
2014-06-19 15:12:24 -04:00
} ,
2020-02-13 15:32:58 -05:00
addrs . AbsProviderConfig {
2020-04-01 15:55:25 -04:00
Provider : addrs . NewDefaultProvider ( "test" ) ,
2020-03-11 14:19:52 -04:00
Module : addrs . RootModule ,
2020-02-13 15:32:58 -05:00
} ,
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
)
} )
2014-06-27 17:43:23 -04:00
statePath := testStateFile ( t , originalState )
2014-06-19 15:12:24 -04:00
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-01-12 16:13:10 -05:00
p . PlanResourceChangeResponse = & providers . PlanResourceChangeResponse {
2018-09-29 12:35:19 -04:00
PlannedState : cty . ObjectVal ( map [ string ] cty . Value {
"ami" : cty . StringVal ( "bar" ) ,
} ) ,
2014-06-30 23:49:49 -04:00
}
2021-01-12 16:13:10 -05:00
p . ApplyResourceChangeResponse = & providers . ApplyResourceChangeResponse {
2018-10-12 19:31:18 -04:00
NewState : cty . ObjectVal ( map [ string ] cty . Value {
"ami" : cty . StringVal ( "bar" ) ,
} ) ,
}
2014-06-30 23:49:49 -04:00
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-06-19 15:12:24 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-06-19 15:12:24 -04:00
}
// Run the apply command pointing to our existing state
args := [ ] string {
2014-07-12 00:30:40 -04:00
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-06-19 15:12:24 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-06-19 15:12:24 -04:00
}
// Verify that the provider was called with the existing state
2018-09-29 12:35:19 -04:00
actual := p . PlanResourceChangeRequest . PriorState
expected := cty . ObjectVal ( map [ string ] cty . Value {
2018-10-12 19:31:18 -04:00
"id" : cty . NullVal ( cty . String ) ,
2018-10-16 20:51:47 -04:00
"ami" : cty . StringVal ( "foo" ) ,
2018-09-29 12:35:19 -04:00
} )
if ! expected . RawEquals ( actual ) {
t . Fatalf ( "wrong prior state during plan\ngot: %#v\nwant: %#v" , actual , expected )
2014-06-19 15:13:47 -04:00
}
2018-09-29 12:35:19 -04:00
actual = p . ApplyResourceChangeRequest . PriorState
expected = cty . ObjectVal ( map [ string ] cty . Value {
2018-10-12 19:31:18 -04:00
"id" : cty . NullVal ( cty . String ) ,
2018-10-16 20:51:47 -04:00
"ami" : cty . StringVal ( "foo" ) ,
2018-09-29 12:35:19 -04:00
} )
2018-10-16 20:51:47 -04:00
if ! expected . RawEquals ( actual ) {
2018-09-29 12:35:19 -04:00
t . Fatalf ( "wrong prior state during apply\ngot: %#v\nwant: %#v" , actual , expected )
2014-06-19 15:12:24 -04:00
}
// Verify a new state exists
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-06-19 15:12:24 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
2014-07-27 23:38:41 -04:00
2017-07-05 17:59:42 -04:00
backupState := testStateRead ( t , statePath + DefaultBackupExtension )
2014-07-27 23:38:41 -04:00
2014-09-18 20:16:09 -04:00
actualStr := strings . TrimSpace ( backupState . String ( ) )
expectedStr := strings . TrimSpace ( originalState . String ( ) )
if actualStr != expectedStr {
t . Fatalf ( "bad:\n\n%s\n\n%s" , actualStr , expectedStr )
2014-07-27 23:38:41 -04:00
}
2014-06-19 15:12:24 -04:00
}
2014-06-19 00:36:44 -04:00
func TestApply_stateNoExist ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-06-19 00:36:44 -04:00
c := & ApplyCommand {
2014-07-12 23:37:30 -04:00
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-12 23:37:30 -04:00
} ,
2014-06-19 00:36:44 -04:00
}
args := [ ] string {
2014-06-27 17:43:23 -04:00
"idontexist.tfstate" ,
2014-06-19 00:36:44 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "bad: \n%s" , output . Stdout ( ) )
2014-06-19 00:36:44 -04:00
}
}
2014-07-18 14:37:27 -04:00
2016-05-09 15:46:07 -04:00
func TestApply_sensitiveOutput ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-sensitive-output" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2016-05-10 14:56:26 -04:00
p := testProvider ( )
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
view , done := testView ( t )
2016-05-10 14:56:26 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2016-05-10 14:56:26 -04:00
} ,
}
2016-05-09 15:46:07 -04:00
statePath := testTempFile ( t )
2016-03-11 14:07:54 -05:00
args := [ ] string {
"-state" , statePath ,
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2016-03-11 14:07:54 -05:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: \n%s" , output . Stdout ( ) )
2016-03-11 14:07:54 -05:00
}
2021-02-18 17:23:34 -05:00
stdout := output . Stdout ( )
if ! strings . Contains ( stdout , "notsensitive = \"Hello world\"" ) {
t . Fatalf ( "bad: output should contain 'notsensitive' output\n%s" , stdout )
2016-03-11 14:07:54 -05:00
}
2021-02-18 17:23:34 -05:00
if ! strings . Contains ( stdout , "sensitive = <sensitive>" ) {
t . Fatalf ( "bad: output should contain 'sensitive' output\n%s" , stdout )
2016-03-11 14:07:54 -05:00
}
}
2014-07-18 14:37:27 -04:00
func TestApply_vars ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-vars" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-07-18 14:37:27 -04:00
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-18 14:37:27 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-18 14:37:27 -04:00
} ,
}
2019-02-11 20:46:55 -05:00
actual := ""
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-10-12 19:31:18 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"value" : { Type : cty . String , Optional : true } ,
} ,
2018-10-12 19:31:18 -04:00
} ,
} ,
} ,
}
2018-10-14 10:59:15 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
2018-10-12 19:31:18 -04:00
return providers . ApplyResourceChangeResponse {
NewState : req . PlannedState ,
}
}
2019-02-11 20:46:55 -05:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
actual = req . ProposedNewState . GetAttr ( "value" ) . AsString ( )
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
2014-07-18 14:37:27 -04:00
}
}
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-18 14:37:27 -04:00
"-var" , "foo=bar" ,
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-18 14:37:27 -04:00
}
if actual != "bar" {
t . Fatal ( "didn't work" )
}
}
2014-07-18 17:00:40 -04:00
func TestApply_varFile ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-vars" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-07-18 17:00:40 -04:00
varFilePath := testTempFile ( t )
if err := ioutil . WriteFile ( varFilePath , [ ] byte ( applyVarFile ) , 0644 ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-18 17:00:40 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-18 17:00:40 -04:00
} ,
}
2019-02-11 20:46:55 -05:00
actual := ""
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-10-12 19:31:18 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"value" : { Type : cty . String , Optional : true } ,
} ,
2018-10-12 19:31:18 -04:00
} ,
} ,
} ,
}
2018-10-14 10:59:15 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
2018-10-12 19:31:18 -04:00
return providers . ApplyResourceChangeResponse {
NewState : req . PlannedState ,
}
}
2019-02-11 20:46:55 -05:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
actual = req . ProposedNewState . GetAttr ( "value" ) . AsString ( )
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
2014-07-18 17:00:40 -04:00
}
}
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-18 17:00:40 -04:00
"-var-file" , varFilePath ,
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-18 17:00:40 -04:00
}
if actual != "bar" {
t . Fatal ( "didn't work" )
}
}
2014-08-05 12:32:01 -04:00
func TestApply_varFileDefault ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-vars" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
varFilePath := filepath . Join ( td , "terraform.tfvars" )
2024-11-18 10:17:18 -05:00
if err := os . WriteFile ( varFilePath , [ ] byte ( applyVarFile ) , 0644 ) ; err != nil {
2014-08-05 12:32:01 -04:00
t . Fatalf ( "err: %s" , err )
}
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-08-05 12:32:01 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-08-05 12:32:01 -04:00
} ,
}
2019-02-11 20:46:55 -05:00
actual := ""
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-10-12 19:31:18 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"value" : { Type : cty . String , Optional : true } ,
} ,
2018-10-12 19:31:18 -04:00
} ,
} ,
} ,
}
2018-10-14 10:59:15 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
2018-10-12 19:31:18 -04:00
return providers . ApplyResourceChangeResponse {
NewState : req . PlannedState ,
}
}
2019-02-11 20:46:55 -05:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
actual = req . ProposedNewState . GetAttr ( "value" ) . AsString ( )
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
2014-08-05 12:32:01 -04:00
}
}
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-08-05 12:32:01 -04:00
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-08-05 12:32:01 -04:00
}
if actual != "bar" {
t . Fatal ( "didn't work" )
}
}
2015-03-02 12:21:45 -05:00
func TestApply_varFileDefaultJSON ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-vars" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
varFilePath := filepath . Join ( td , "terraform.tfvars.json" )
2015-03-02 12:21:45 -05:00
if err := ioutil . WriteFile ( varFilePath , [ ] byte ( applyVarFileJSON ) , 0644 ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2015-03-02 12:21:45 -05:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2015-03-02 12:21:45 -05:00
} ,
}
2019-02-11 20:46:55 -05:00
actual := ""
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-10-12 19:31:18 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"value" : { Type : cty . String , Optional : true } ,
} ,
2018-10-12 19:31:18 -04:00
} ,
} ,
} ,
}
2018-10-14 10:59:15 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
2018-10-12 19:31:18 -04:00
return providers . ApplyResourceChangeResponse {
NewState : req . PlannedState ,
}
}
2019-02-11 20:46:55 -05:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
actual = req . ProposedNewState . GetAttr ( "value" ) . AsString ( )
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
2015-03-02 12:21:45 -05:00
}
}
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2015-03-02 12:21:45 -05:00
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2015-03-02 12:21:45 -05:00
}
if actual != "bar" {
t . Fatal ( "didn't work" )
}
}
2014-07-27 23:38:41 -04:00
func TestApply_backup ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
originalState := 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 {
2018-10-12 19:31:18 -04:00
AttrsJSON : [ ] byte ( "{\n \"id\": \"bar\"\n }" ) ,
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
Status : states . ObjectReady ,
2014-07-27 23:38:41 -04:00
} ,
2020-02-13 15:32:58 -05:00
addrs . AbsProviderConfig {
2020-04-01 15:55:25 -04:00
Provider : addrs . NewDefaultProvider ( "test" ) ,
2020-03-11 14:19:52 -04:00
Module : addrs . RootModule ,
2020-02-13 15:32:58 -05:00
} ,
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 17:24:45 -04:00
)
} )
2014-07-27 23:38:41 -04:00
statePath := testStateFile ( t , originalState )
backupPath := testTempFile ( t )
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-01-12 16:13:10 -05:00
p . PlanResourceChangeResponse = & providers . PlanResourceChangeResponse {
2018-09-29 12:35:19 -04:00
PlannedState : cty . ObjectVal ( map [ string ] cty . Value {
"ami" : cty . StringVal ( "bar" ) ,
} ) ,
2014-07-27 23:38:41 -04:00
}
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-27 23:38:41 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-27 23:38:41 -04:00
} ,
}
// Run the apply command pointing to our existing state
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-27 23:38:41 -04:00
"-state" , statePath ,
"-backup" , backupPath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-27 23:38:41 -04:00
}
// Verify a new state exists
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-27 23:38:41 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
2017-07-05 17:59:42 -04:00
backupState := testStateRead ( t , backupPath )
2014-07-27 23:38:41 -04:00
2014-09-17 14:15:07 -04:00
actual := backupState . RootModule ( ) . Resources [ "test_instance.foo" ]
expected := originalState . RootModule ( ) . Resources [ "test_instance.foo" ]
2024-08-21 15:30:01 -04:00
if ! cmp . Equal ( actual , expected , cmpopts . EquateEmpty ( ) , cmpopts . IgnoreUnexported ( states . ResourceInstanceObjectSrc { } ) ) {
2018-10-12 19:31:18 -04:00
t . Fatalf (
"wrong aws_instance.foo state\n%s" ,
2018-10-14 10:59:15 -04:00
cmp . Diff ( expected , actual , cmp . Transformer ( "bytesAsString" , func ( b [ ] byte ) string {
2018-10-12 19:31:18 -04:00
return string ( b )
} ) ) ,
)
2014-07-27 23:38:41 -04:00
}
}
func TestApply_disableBackup ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2014-09-18 13:40:23 -04:00
originalState := testState ( )
2014-07-27 23:38:41 -04:00
statePath := testStateFile ( t , originalState )
2018-10-11 20:58:46 -04:00
p := applyFixtureProvider ( )
2021-01-12 16:13:10 -05:00
p . PlanResourceChangeResponse = & providers . PlanResourceChangeResponse {
2018-09-29 12:35:19 -04:00
PlannedState : cty . ObjectVal ( map [ string ] cty . Value {
"ami" : cty . StringVal ( "bar" ) ,
} ) ,
2014-07-27 23:38:41 -04:00
}
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2014-07-27 23:38:41 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2014-07-27 23:38:41 -04:00
} ,
}
// Run the apply command pointing to our existing state
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2014-07-27 23:38:41 -04:00
"-state" , statePath ,
"-backup" , "-" ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2014-07-27 23:38:41 -04:00
}
// Verify that the provider was called with the existing state
2018-09-29 12:35:19 -04:00
actual := p . PlanResourceChangeRequest . PriorState
expected := cty . ObjectVal ( map [ string ] cty . Value {
2018-10-12 19:31:18 -04:00
"id" : cty . StringVal ( "bar" ) ,
"ami" : cty . NullVal ( cty . String ) ,
2018-09-29 12:35:19 -04:00
} )
2018-10-12 19:31:18 -04:00
if ! expected . RawEquals ( actual ) {
2018-09-29 12:35:19 -04:00
t . Fatalf ( "wrong prior state during plan\ngot: %#v\nwant: %#v" , actual , expected )
2014-07-27 23:38:41 -04:00
}
2018-09-29 12:35:19 -04:00
actual = p . ApplyResourceChangeRequest . PriorState
expected = cty . ObjectVal ( map [ string ] cty . Value {
2018-10-14 10:59:15 -04:00
"id" : cty . StringVal ( "bar" ) ,
2018-10-12 19:31:18 -04:00
"ami" : cty . NullVal ( cty . String ) ,
2018-09-29 12:35:19 -04:00
} )
2018-10-12 19:31:18 -04:00
if ! expected . RawEquals ( actual ) {
2018-09-29 12:35:19 -04:00
t . Fatalf ( "wrong prior state during apply\ngot: %#v\nwant: %#v" , actual , expected )
2014-07-27 23:38:41 -04:00
}
// Verify a new state exists
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
2017-07-05 17:59:42 -04:00
state := testStateRead ( t , statePath )
2014-07-27 23:38:41 -04:00
if state == nil {
t . Fatal ( "state should not be nil" )
}
// Ensure there is no backup
2017-07-05 17:59:42 -04:00
_ , err := os . Stat ( statePath + DefaultBackupExtension )
2014-07-27 23:38:41 -04:00
if err == nil || ! os . IsNotExist ( err ) {
t . Fatalf ( "backup should not exist" )
}
2015-03-02 12:11:49 -05:00
// Ensure there is no literal "-"
_ , err = os . Stat ( "-" )
if err == nil || ! os . IsNotExist ( err ) {
t . Fatalf ( "backup should not exist" )
}
2014-07-27 23:38:41 -04:00
}
2017-03-13 19:25:27 -04:00
// Test that the Terraform env is passed through
func TestApply_terraformEnv ( t * testing . T ) {
2021-02-02 10:35:45 -05:00
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-terraform-env" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-02 10:35:45 -05:00
2017-03-13 19:25:27 -04:00
statePath := testTempFile ( t )
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2017-03-13 19:25:27 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2017-03-13 19:25:27 -04:00
} ,
}
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2017-03-13 19:25:27 -04:00
"-state" , statePath ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2017-03-13 19:25:27 -04:00
}
expected := strings . TrimSpace ( `
< no state >
Outputs :
output = default
` )
testStateOutput ( t , statePath , expected )
}
// Test that the Terraform env is passed through
func TestApply_terraformEnvNonDefault ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-02 10:35:45 -05:00
testCopyDir ( t , testFixturePath ( "apply-terraform-env" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2017-03-13 19:25:27 -04:00
// Create new env
{
ui := new ( cli . MockUi )
2021-02-18 17:23:34 -05:00
newCmd := & WorkspaceNewCommand {
Meta : Meta {
Ui : ui ,
} ,
}
2017-03-13 19:25:27 -04:00
if code := newCmd . Run ( [ ] string { "test" } ) ; code != 0 {
2021-08-31 17:33:26 -04:00
t . Fatal ( "error creating workspace" )
2017-03-13 19:25:27 -04:00
}
}
// Switch to it
{
args := [ ] string { "test" }
ui := new ( cli . MockUi )
2021-02-18 17:23:34 -05:00
selCmd := & WorkspaceSelectCommand {
Meta : Meta {
Ui : ui ,
} ,
}
2017-03-13 19:25:27 -04:00
if code := selCmd . Run ( args ) ; code != 0 {
2021-08-31 17:33:26 -04:00
t . Fatal ( "error switching workspace" )
2017-03-13 19:25:27 -04:00
}
}
p := testProvider ( )
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2017-03-13 19:25:27 -04:00
c := & ApplyCommand {
Meta : Meta {
2017-04-13 21:05:58 -04:00
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2017-03-13 19:25:27 -04:00
} ,
}
args := [ ] string {
2017-10-30 16:33:27 -04:00
"-auto-approve" ,
2017-03-13 19:25:27 -04:00
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2017-03-13 19:25:27 -04:00
}
statePath := filepath . Join ( "terraform.tfstate.d" , "test" , "terraform.tfstate" )
expected := strings . TrimSpace ( `
< no state >
Outputs :
output = test
` )
testStateOutput ( t , statePath , expected )
}
2021-02-08 13:29:42 -05:00
// Config with multiple resources, targeting apply of a subset
func TestApply_targeted ( t * testing . T ) {
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-08 13:29:42 -05:00
testCopyDir ( t , testFixturePath ( "apply-targeted" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-08 13:29:42 -05:00
p := testProvider ( )
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
2021-02-08 13:29:42 -05:00
ResourceTypes : map [ string ] providers . Schema {
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-02-08 13:29:42 -05:00
Attributes : map [ string ] * configschema . Attribute {
"id" : { Type : cty . String , Computed : true } ,
} ,
} ,
} ,
} ,
}
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
}
}
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2021-02-08 13:29:42 -05:00
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2021-02-08 13:29:42 -05:00
} ,
}
args := [ ] string {
"-auto-approve" ,
"-target" , "test_instance.foo" ,
"-target" , "test_instance.baz" ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2021-02-08 13:29:42 -05:00
}
2021-02-18 17:23:34 -05:00
if got , want := output . Stdout ( ) , "3 added, 0 changed, 0 destroyed" ; ! strings . Contains ( got , want ) {
2021-02-08 13:29:42 -05:00
t . Fatalf ( "bad change summary, want %q, got:\n%s" , want , got )
}
}
// Diagnostics for invalid -target flags
func TestApply_targetFlagsDiags ( t * testing . T ) {
testCases := map [ string ] string {
"test_instance." : "Dot must be followed by attribute name." ,
"test_instance" : "Resource specification must include a resource type and name." ,
}
for target , wantDiag := range testCases {
t . Run ( target , func ( t * testing . T ) {
td := testTempDir ( t )
defer os . RemoveAll ( td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-08 13:29:42 -05:00
2021-02-18 17:23:34 -05:00
view , done := testView ( t )
2021-02-08 13:29:42 -05:00
c := & ApplyCommand {
Meta : Meta {
cli: Add initial command views abstraction
Terraform supports multiple output formats for several sub-commands.
The default format is user-readable text, but many sub-commands support
a `-json` flag to output a machine-readable format for the result. The
output command also supports a `-raw` flag for a simpler, scripting-
focused machine readable format.
This commit adds a "views" abstraction, intended to help ensure
consistency between the various output formats. This extracts the render
specific code from the command package, and moves it into a views
package. Each command is expected to create an interface for its view,
and one or more implementations of that interface.
By doing so, we separate the concerns of generating the sub-command
result from rendering the result in the specified output format. This
should make it easier to ensure that all output formats will be updated
together when changes occur in the result-generating phase.
There are some other consequences of this restructuring:
- Views now directly access the terminal streams, rather than the
now-redundant cli.Ui instance;
- With the reorganization of commands, parsing CLI arguments is now the
responsibility of a separate "arguments" package.
For now, views are added only for the output sub-command, as an example.
Because this command uses code which is shared with the apply and
refresh commands, those are also partially updated.
2021-01-27 15:51:40 -05:00
View : view ,
2021-02-08 13:29:42 -05:00
} ,
}
args := [ ] string {
"-auto-approve" ,
"-target" , target ,
}
2021-02-18 17:23:34 -05:00
code := c . Run ( args )
output := done ( t )
if code != 1 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
2021-02-08 13:29:42 -05:00
}
2021-02-18 17:23:34 -05:00
got := output . Stderr ( )
2021-02-08 13:29:42 -05:00
if ! strings . Contains ( got , target ) {
t . Fatalf ( "bad error output, want %q, got:\n%s" , target , got )
}
if ! strings . Contains ( got , wantDiag ) {
t . Fatalf ( "bad error output, want %q, got:\n%s" , wantDiag , got )
}
} )
}
}
2021-04-30 17:46:22 -04:00
func TestApply_replace ( t * testing . T ) {
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-04-30 17:46:22 -04:00
testCopyDir ( t , testFixturePath ( "apply-replace" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-04-30 17:46:22 -04:00
originalState := states . BuildState ( func ( s * states . SyncState ) {
s . SetResourceInstanceCurrent (
addrs . Resource {
Mode : addrs . ManagedResourceMode ,
Type : "test_instance" ,
Name : "a" ,
} . Instance ( addrs . NoKey ) . Absolute ( addrs . RootModuleInstance ) ,
& states . ResourceInstanceObjectSrc {
AttrsJSON : [ ] byte ( ` { "id":"hello"} ` ) ,
Status : states . ObjectReady ,
} ,
addrs . AbsProviderConfig {
Provider : addrs . NewDefaultProvider ( "test" ) ,
Module : addrs . RootModule ,
} ,
)
} )
statePath := testStateFile ( t , originalState )
p := testProvider ( )
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
ResourceTypes : map [ string ] providers . Schema {
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-04-30 17:46:22 -04:00
Attributes : map [ string ] * configschema . Attribute {
"id" : { Type : cty . String , Computed : true } ,
} ,
} ,
} ,
} ,
}
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
}
}
createCount := 0
deleteCount := 0
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
if req . PriorState . IsNull ( ) {
createCount ++
}
if req . PlannedState . IsNull ( ) {
deleteCount ++
}
return providers . ApplyResourceChangeResponse {
NewState : req . PlannedState ,
}
}
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-auto-approve" ,
"-state" , statePath ,
"-replace" , "test_instance.a" ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "wrong exit code %d\n\n%s" , code , output . Stderr ( ) )
}
if got , want := output . Stdout ( ) , "1 added, 0 changed, 1 destroyed" ; ! strings . Contains ( got , want ) {
t . Errorf ( "wrong change summary\ngot output:\n%s\n\nwant substring: %s" , got , want )
}
if got , want := createCount , 1 ; got != want {
t . Errorf ( "wrong create count %d; want %d" , got , want )
}
if got , want := deleteCount , 1 ; got != want {
t . Errorf ( "wrong create count %d; want %d" , got , want )
}
}
2021-02-18 17:23:34 -05:00
func TestApply_pluginPath ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-18 17:23:34 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-18 17:23:34 -05:00
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
pluginPath := [ ] string { "a" , "b" , "c" }
if err := c . Meta . storePluginPath ( pluginPath ) ; err != nil {
t . Fatal ( err )
}
c . Meta . pluginPath = nil
args := [ ] string {
"-state" , statePath ,
"-auto-approve" ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
}
if ! reflect . DeepEqual ( pluginPath , c . Meta . pluginPath ) {
t . Fatalf ( "expected plugin path %#v, got %#v" , pluginPath , c . Meta . pluginPath )
}
}
2021-02-23 10:16:09 -05:00
func TestApply_jsonGoldenReference ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-02-23 10:16:09 -05:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-02-23 10:16:09 -05:00
statePath := testTempFile ( t )
p := applyFixtureProvider ( )
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-json" ,
"-state" , statePath ,
"-auto-approve" ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
}
if _ , err := os . Stat ( statePath ) ; err != nil {
t . Fatalf ( "err: %s" , err )
}
state := testStateRead ( t , statePath )
if state == nil {
t . Fatal ( "state should not be nil" )
}
2022-07-12 17:00:36 -04:00
checkGoldenReference ( t , output , "apply" )
2021-02-23 10:16:09 -05:00
}
2021-05-05 14:13:20 -04:00
func TestApply_warnings ( t * testing . T ) {
// Create a temporary working directory that is empty
2022-04-08 12:34:16 -04:00
td := t . TempDir ( )
2021-05-05 14:13:20 -04:00
testCopyDir ( t , testFixturePath ( "apply" ) , td )
2025-07-16 11:04:10 -04:00
t . Chdir ( td )
2021-05-05 14:13:20 -04:00
p := testProvider ( )
p . GetProviderSchemaResponse = applyFixtureSchema ( )
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
Diagnostics : tfdiags . Diagnostics {
tfdiags . SimpleWarning ( "warning 1" ) ,
tfdiags . SimpleWarning ( "warning 2" ) ,
} ,
}
}
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
return providers . ApplyResourceChangeResponse {
NewState : cty . UnknownAsNull ( req . PlannedState ) ,
}
}
t . Run ( "full warnings" , func ( t * testing . T ) {
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string { "-auto-approve" }
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
}
wantWarnings := [ ] string {
"warning 1" ,
"warning 2" ,
}
for _ , want := range wantWarnings {
if ! strings . Contains ( output . Stdout ( ) , want ) {
t . Errorf ( "missing warning %s" , want )
}
}
} )
t . Run ( "compact warnings" , func ( t * testing . T ) {
view , done := testView ( t )
c := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
code := c . Run ( [ ] string { "-auto-approve" , "-compact-warnings" } )
output := done ( t )
if code != 0 {
t . Fatalf ( "bad: %d\n\n%s" , code , output . Stderr ( ) )
}
// the output should contain 2 warnings and a message about -compact-warnings
wantWarnings := [ ] string {
"warning 1" ,
"warning 2" ,
"To see the full warning notes, run Terraform without -compact-warnings." ,
}
for _ , want := range wantWarnings {
if ! strings . Contains ( output . Stdout ( ) , want ) {
t . Errorf ( "missing warning %s" , want )
}
}
} )
}
2018-05-22 22:33:45 -04:00
// applyFixtureSchema returns a schema suitable for processing the
2019-06-30 03:38:36 -04:00
// configuration in testdata/apply . This schema should be
2018-05-22 22:33:45 -04:00
// assigned to a mock provider named "test".
2021-02-18 10:13:43 -05:00
func applyFixtureSchema ( ) * providers . GetProviderSchemaResponse {
return & providers . GetProviderSchemaResponse {
2021-01-12 16:13:10 -05:00
ResourceTypes : map [ string ] providers . Schema {
2018-05-22 22:33:45 -04:00
"test_instance" : {
2025-03-04 10:33:43 -05:00
Body : & configschema . Block {
2021-01-12 16:13:10 -05:00
Attributes : map [ string ] * configschema . Attribute {
"id" : { Type : cty . String , Optional : true , Computed : true } ,
"ami" : { Type : cty . String , Optional : true } ,
} ,
2018-05-22 22:33:45 -04:00
} ,
} ,
} ,
}
}
2018-10-11 20:58:46 -04:00
// applyFixtureProvider returns a mock provider that is configured for basic
2019-06-30 03:38:36 -04:00
// operation with the configuration in testdata/apply. This mock has
2021-01-12 16:13:10 -05:00
// GetSchemaResponse, PlanResourceChangeFn, and ApplyResourceChangeFn populated,
2018-10-11 20:58:46 -04:00
// with the plan/apply steps just passing through the data determined by
// Terraform Core.
2024-02-16 04:35:29 -05:00
func applyFixtureProvider ( ) * testing_provider . MockProvider {
2018-10-11 20:58:46 -04:00
p := testProvider ( )
2021-02-18 10:13:43 -05:00
p . GetProviderSchemaResponse = applyFixtureSchema ( )
2018-10-14 10:59:15 -04:00
p . PlanResourceChangeFn = func ( req providers . PlanResourceChangeRequest ) providers . PlanResourceChangeResponse {
2018-10-11 20:58:46 -04:00
return providers . PlanResourceChangeResponse {
PlannedState : req . ProposedNewState ,
}
}
2018-10-14 10:59:15 -04:00
p . ApplyResourceChangeFn = func ( req providers . ApplyResourceChangeRequest ) providers . ApplyResourceChangeResponse {
2018-10-11 20:58:46 -04:00
return providers . ApplyResourceChangeResponse {
2018-10-12 19:31:18 -04:00
NewState : cty . UnknownAsNull ( req . PlannedState ) ,
2018-10-11 20:58:46 -04:00
}
}
return p
}
2018-10-12 21:04:26 -04:00
// applyFixturePlanFile creates a plan file at a temporary location containing
// a single change to create the test_instance.foo that is included in the
// "apply" test fixture, returning the location of that plan file.
func applyFixturePlanFile ( t * testing . T ) string {
2021-10-13 17:28:14 -04:00
return applyFixturePlanFileMatchState ( t , statemgr . SnapshotMeta { } )
}
// applyFixturePlanFileMatchState creates a planfile like applyFixturePlanFile,
// but inserts the state meta information if that plan must match a preexisting
// state.
func applyFixturePlanFileMatchState ( t * testing . T , stateMeta statemgr . SnapshotMeta ) string {
2018-10-12 21:04:26 -04:00
_ , snap := testModuleWithSnapshot ( t , "apply" )
plannedVal := cty . ObjectVal ( map [ string ] cty . Value {
"id" : cty . UnknownVal ( cty . String ) ,
"ami" : cty . StringVal ( "bar" ) ,
} )
priorValRaw , err := plans . NewDynamicValue ( cty . NullVal ( plannedVal . Type ( ) ) , plannedVal . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plannedValRaw , err := plans . NewDynamicValue ( plannedVal , plannedVal . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plan := testPlan ( t )
2024-08-12 14:28:26 -04:00
plan . Changes . AppendResourceInstanceChange ( & plans . ResourceInstanceChangeSrc {
2018-10-12 21:04:26 -04:00
Addr : addrs . Resource {
Mode : addrs . ManagedResourceMode ,
Type : "test_instance" ,
Name : "foo" ,
} . Instance ( addrs . NoKey ) . Absolute ( addrs . RootModuleInstance ) ,
2020-02-13 15:32:58 -05:00
ProviderAddr : addrs . AbsProviderConfig {
2020-04-01 15:55:25 -04:00
Provider : addrs . NewDefaultProvider ( "test" ) ,
2020-03-11 14:19:52 -04:00
Module : addrs . RootModule ,
2020-02-13 15:32:58 -05:00
} ,
2018-10-12 21:04:26 -04:00
ChangeSrc : plans . ChangeSrc {
Action : plans . Create ,
Before : priorValRaw ,
After : plannedValRaw ,
} ,
} )
2021-10-13 17:28:14 -04:00
return testPlanFileMatchState (
2018-10-12 21:04:26 -04:00
t ,
snap ,
states . NewState ( ) ,
plan ,
2021-10-13 17:28:14 -04:00
stateMeta ,
2018-10-12 21:04:26 -04:00
)
}
2024-11-04 08:32:15 -05:00
// applyFixturePlanFileWithVariableValue creates a plan file at a temporary location containing
// a single change to create the test_instance.foo and a variable value that is included in the
// "apply" test fixture, returning the location of that plan file.
func applyFixturePlanFileWithVariableValue ( t * testing . T , value string ) string {
2024-11-17 12:45:41 -05:00
_ , snap := testModuleWithSnapshot ( t , "apply-vars" )
2024-11-04 08:32:15 -05:00
plannedVal := cty . ObjectVal ( map [ string ] cty . Value {
2024-11-18 10:17:18 -05:00
"id" : cty . UnknownVal ( cty . String ) ,
"value" : cty . StringVal ( "bar" ) ,
2024-11-04 08:32:15 -05:00
} )
priorValRaw , err := plans . NewDynamicValue ( cty . NullVal ( plannedVal . Type ( ) ) , plannedVal . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plannedValRaw , err := plans . NewDynamicValue ( plannedVal , plannedVal . Type ( ) )
if err != nil {
t . Fatal ( err )
}
plan := testPlan ( t )
plan . Changes . AppendResourceInstanceChange ( & plans . ResourceInstanceChangeSrc {
Addr : addrs . Resource {
Mode : addrs . ManagedResourceMode ,
Type : "test_instance" ,
Name : "foo" ,
} . Instance ( addrs . NoKey ) . Absolute ( addrs . RootModuleInstance ) ,
ProviderAddr : addrs . AbsProviderConfig {
Provider : addrs . NewDefaultProvider ( "test" ) ,
Module : addrs . RootModule ,
} ,
ChangeSrc : plans . ChangeSrc {
Action : plans . Create ,
Before : priorValRaw ,
After : plannedValRaw ,
} ,
} )
plan . VariableValues = map [ string ] plans . DynamicValue {
"foo" : mustNewDynamicValue ( value , cty . DynamicPseudoType ) ,
}
return testPlanFileMatchState (
t ,
snap ,
states . NewState ( ) ,
plan ,
statemgr . SnapshotMeta { } ,
)
}
2014-07-18 17:00:40 -04:00
const applyVarFile = `
foo = "bar"
`
2014-09-18 13:40:23 -04:00
2015-03-02 12:21:45 -05:00
const applyVarFileJSON = `
{ "foo" : "bar" }
`
2024-11-04 08:32:15 -05:00
func mustNewDynamicValue ( val string , ty cty . Type ) plans . DynamicValue {
realVal := cty . StringVal ( val )
ret , err := plans . NewDynamicValue ( realVal , ty )
if err != nil {
panic ( err )
}
return ret
}
2025-10-31 12:59:43 -04:00
func TestProviderInconsistentFileFunc ( t * testing . T ) {
// Verify that providers can still accept inconsistent results from
// filesystem functions. We allow this for backwards compatibility, but
// ephemeral values should be used in the long-term to allow for controlled
// changes in values between plan and apply.
td := t . TempDir ( )
planDir := filepath . Join ( td , "plan" )
applyDir := filepath . Join ( td , "apply" )
testCopyDir ( t , testFixturePath ( "changed-file-func-plan" ) , planDir )
testCopyDir ( t , testFixturePath ( "changed-file-func-apply" ) , applyDir )
t . Chdir ( planDir )
p := planVarsFixtureProvider ( )
p . GetProviderSchemaResponse = & providers . GetProviderSchemaResponse {
Provider : providers . Schema {
Body : & configschema . Block {
Attributes : map [ string ] * configschema . Attribute {
"foo" : { Type : cty . String , Optional : true } ,
} ,
} ,
} ,
ResourceTypes : map [ string ] providers . Schema {
"test_instance" : {
Body : & configschema . Block {
Attributes : map [ string ] * configschema . Attribute {
"id" : { Type : cty . String , Optional : true , Computed : true } ,
} ,
} ,
} ,
} ,
}
view , done := testView ( t )
c := & PlanCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
View : view ,
} ,
}
args := [ ] string {
"-out" , filepath . Join ( applyDir , "planfile" ) ,
}
code := c . Run ( args )
output := done ( t )
if code != 0 {
t . Fatalf ( "non-zero exit %d\n\n%s" , code , output . Stderr ( ) )
}
t . Chdir ( applyDir )
view , done = testView ( t )
apply := & ApplyCommand {
Meta : Meta {
testingOverrides : metaOverridesForProvider ( p ) ,
Ui : new ( cli . MockUi ) ,
View : view ,
} ,
}
args = [ ] string {
"planfile" ,
}
code = apply . Run ( args )
output = done ( t )
if code != 0 {
t . Fatalf ( "non-zero exit %d\n\n%s" , code , output . Stderr ( ) )
}
}