mirror of https://github.com/hashicorp/terraform
Going back a long time we've had a special magic behavior which tries to recognize a situation where a module author either added or removed the "count" argument from a resource that already has instances, and to silently rename the zeroth or no-key instance so that we don't plan to destroy and recreate the associated object. Now we have a more general idea of "move statements", and specifically the idea of "implied" move statements which replicates the same heuristic we used to use for this behavior, we can treat this magic renaming rule as just another "move statement", special only in that Terraform generates it automatically rather than it being written out explicitly in the configuration. In return for wiring that in, we can now remove altogether the NodeCountBoundary graph node type and its associated graph transformer, CountBoundaryTransformer. We handle moves as a preprocessing step before building the plan graph, so we no longer need to include any special nodes in the graph to deal with that situation. The test updates here are mainly for the graph builders themselves, to acknowledge that indeed we're no longer inserting the NodeCountBoundary vertices. The vertices that NodeCountBoundary previously depended on now become dependencies of the special "root" vertex, although in many cases here we don't see that explicitly because of the transitive reduction algorithm, which notices when there's already an equivalent indirect dependency chain and removes the redundant edge. We already have plenty of test coverage for these "count boundary" cases in the context tests whose names start with TestContext2Plan_count and TestContext2Apply_resourceCount, all of which continued to pass here without any modification and so are not visible in the diff. The test functions particularly relevant to this situation are: - TestContext2Plan_countIncreaseFromNotSet - TestContext2Plan_countDecreaseToOne - TestContext2Plan_countOneIndex - TestContext2Apply_countDecreaseToOneCorrupted The last of those in particular deals with the situation where we have both a no-key instance _and_ a zero-key instance in the prior state, which is interesting here because to exercises an intentional interaction between refactoring.ImpliedMoveStatements and refactoring.ApplyMoves, where we intentionally generate an implied move statement that produces a collision and then expect ApplyMoves to deal with it in the same way as it would deal with all other collisions, and thus ensure we handle both the explicit and implied collisions in the same way. This does affect some UI-level tests, because a nice side-effect of this new treatment of this old feature is that we can now report explicitly in the UI that we're assigning new addresses to these objects, whereas before we just said nothing and hoped the user would just guess what had happened and why they therefore weren't seeing a diff. The backend/local plan tests actually had a pre-existing bug where they were using a state with a different instance key than the config called for but getting away with it because we'd previously silently fix it up. That's still fixed up, but now done with an explicit mention in the UI and so I made the state consistent with the configuration here so that the tests would be able to recognize _real_ differences where present, as opposed to the errant difference caused by that inconsistency.pull/29603/head
parent
ee9e346039
commit
f0034beb33
@ -1,80 +0,0 @@
|
||||
package terraform
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/hashicorp/terraform/internal/addrs"
|
||||
"github.com/hashicorp/terraform/internal/configs"
|
||||
"github.com/hashicorp/terraform/internal/tfdiags"
|
||||
)
|
||||
|
||||
// NodeCountBoundary fixes up any transitions between "each modes" in objects
|
||||
// saved in state, such as switching from NoEach to EachInt.
|
||||
type NodeCountBoundary struct {
|
||||
Config *configs.Config
|
||||
}
|
||||
|
||||
var _ GraphNodeExecutable = (*NodeCountBoundary)(nil)
|
||||
|
||||
func (n *NodeCountBoundary) Name() string {
|
||||
return "meta.count-boundary (EachMode fixup)"
|
||||
}
|
||||
|
||||
// GraphNodeExecutable
|
||||
func (n *NodeCountBoundary) Execute(ctx EvalContext, op walkOperation) (diags tfdiags.Diagnostics) {
|
||||
// We'll temporarily lock the state to grab the modules, then work on each
|
||||
// one separately while taking a lock again for each separate resource.
|
||||
// This means that if another caller concurrently adds a module here while
|
||||
// we're working then we won't update it, but that's no worse than the
|
||||
// concurrent writer blocking for our entire fixup process and _then_
|
||||
// adding a new module, and in practice the graph node associated with
|
||||
// this eval depends on everything else in the graph anyway, so there
|
||||
// should not be concurrent writers.
|
||||
state := ctx.State().Lock()
|
||||
moduleAddrs := make([]addrs.ModuleInstance, 0, len(state.Modules))
|
||||
for _, m := range state.Modules {
|
||||
moduleAddrs = append(moduleAddrs, m.Addr)
|
||||
}
|
||||
ctx.State().Unlock()
|
||||
|
||||
for _, addr := range moduleAddrs {
|
||||
cfg := n.Config.DescendentForInstance(addr)
|
||||
if cfg == nil {
|
||||
log.Printf("[WARN] Not fixing up EachModes for %s because it has no config", addr)
|
||||
continue
|
||||
}
|
||||
if err := n.fixModule(ctx, addr); err != nil {
|
||||
diags = diags.Append(err)
|
||||
return diags
|
||||
}
|
||||
}
|
||||
return diags
|
||||
}
|
||||
|
||||
func (n *NodeCountBoundary) fixModule(ctx EvalContext, moduleAddr addrs.ModuleInstance) error {
|
||||
ms := ctx.State().Module(moduleAddr)
|
||||
cfg := n.Config.DescendentForInstance(moduleAddr)
|
||||
if ms == nil {
|
||||
// Theoretically possible for a concurrent writer to delete a module
|
||||
// while we're running, but in practice the graph node that called us
|
||||
// depends on everything else in the graph and so there can never
|
||||
// be a concurrent writer.
|
||||
return fmt.Errorf("[WARN] no state found for %s while trying to fix up EachModes", moduleAddr)
|
||||
}
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("[WARN] no config found for %s while trying to fix up EachModes", moduleAddr)
|
||||
}
|
||||
|
||||
for _, r := range ms.Resources {
|
||||
rCfg := cfg.Module.ResourceByAddr(r.Addr.Resource)
|
||||
if rCfg == nil {
|
||||
log.Printf("[WARN] Not fixing up EachModes for %s because it has no config", r.Addr)
|
||||
continue
|
||||
}
|
||||
hasCount := rCfg.Count != nil
|
||||
fixResourceCountSetTransition(ctx, r.Addr.Config(), hasCount)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@ -1,72 +0,0 @@
|
||||
package terraform
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/hcl/v2/hcltest"
|
||||
"github.com/hashicorp/terraform/internal/addrs"
|
||||
"github.com/hashicorp/terraform/internal/configs"
|
||||
"github.com/hashicorp/terraform/internal/states"
|
||||
"github.com/zclconf/go-cty/cty"
|
||||
)
|
||||
|
||||
func TestNodeCountBoundaryExecute(t *testing.T) {
|
||||
|
||||
// Create a state with a single instance (addrs.NoKey) of test_instance.foo
|
||||
state := states.NewState()
|
||||
state.Module(addrs.RootModuleInstance).SetResourceInstanceCurrent(
|
||||
addrs.Resource{
|
||||
Mode: addrs.ManagedResourceMode,
|
||||
Type: "test_instance",
|
||||
Name: "foo",
|
||||
}.Instance(addrs.NoKey),
|
||||
&states.ResourceInstanceObjectSrc{
|
||||
Status: states.ObjectReady,
|
||||
AttrsJSON: []byte(`{"type":"string","value":"hello"}`),
|
||||
},
|
||||
addrs.AbsProviderConfig{
|
||||
Provider: addrs.NewDefaultProvider("test"),
|
||||
Module: addrs.RootModule,
|
||||
},
|
||||
)
|
||||
|
||||
// Create a config that uses count to create 2 instances of test_instance.foo
|
||||
rc := &configs.Resource{
|
||||
Mode: addrs.ManagedResourceMode,
|
||||
Type: "test_instance",
|
||||
Name: "foo",
|
||||
Count: hcltest.MockExprLiteral(cty.NumberIntVal(2)),
|
||||
Config: configs.SynthBody("", map[string]cty.Value{
|
||||
"test_string": cty.StringVal("hello"),
|
||||
}),
|
||||
}
|
||||
config := &configs.Config{
|
||||
Module: &configs.Module{
|
||||
ManagedResources: map[string]*configs.Resource{
|
||||
"test_instance.foo": rc,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ctx := &MockEvalContext{
|
||||
StateState: state.SyncWrapper(),
|
||||
}
|
||||
node := NodeCountBoundary{Config: config}
|
||||
|
||||
diags := node.Execute(ctx, walkApply)
|
||||
if diags.HasErrors() {
|
||||
t.Fatalf("unexpected error: %s", diags.Err())
|
||||
}
|
||||
if !state.HasResources() {
|
||||
t.Fatal("resources missing from state")
|
||||
}
|
||||
|
||||
// verify that the resource changed from test_instance.foo to
|
||||
// test_instance.foo.0 in the state
|
||||
actual := state.String()
|
||||
expected := "test_instance.foo.0:\n ID = \n provider = provider[\"registry.terraform.io/hashicorp/test\"]\n type = string\n value = hello"
|
||||
|
||||
if actual != expected {
|
||||
t.Fatalf("wrong result: %s", actual)
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
package terraform
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/terraform/internal/configs"
|
||||
"github.com/hashicorp/terraform/internal/dag"
|
||||
)
|
||||
|
||||
// CountBoundaryTransformer adds a node that depends on everything else
|
||||
// so that it runs last in order to clean up the state for nodes that
|
||||
// are on the "count boundary": "foo.0" when only one exists becomes "foo"
|
||||
type CountBoundaryTransformer struct {
|
||||
Config *configs.Config
|
||||
}
|
||||
|
||||
func (t *CountBoundaryTransformer) Transform(g *Graph) error {
|
||||
node := &NodeCountBoundary{
|
||||
Config: t.Config,
|
||||
}
|
||||
g.Add(node)
|
||||
|
||||
// Depends on everything
|
||||
for _, v := range g.Vertices() {
|
||||
// Don't connect to ourselves
|
||||
if v == node {
|
||||
continue
|
||||
}
|
||||
|
||||
// Connect!
|
||||
g.Connect(dag.BasicEdge(node, v))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Loading…
Reference in new issue