command/format: improve consistency of plan results

Previously the rendered plan output was constructed directly from the
core plan and then annotated with counts derived from the count hook.
At various places we applied little adjustments to deal with the fact that
the user-facing diff model is not identical to the internal diff model,
including the special handling of data source reads and destroys. Since
this logic was just muddled into the rendering code, it behaved
inconsistently with the tally of adds, updates and deletes.

This change reworks the plan formatter so that it happens in two stages:
- First, we produce a specialized Plan object that is tailored for use
  in the UI. This applies all the relevant logic to transform the
  physical model into the user model.
- Second, we do a straightforward visual rendering of the display-oriented
  plan object.

For the moment this is slightly overkill since there's only one rendering
path, but it does give us the benefit of letting the counts be derived
from the same data as the full detailed diff, ensuring that they'll stay
consistent.

Later we may choose to have other UIs for plans, such as a
machine-readable output intended to drive a web UI. In that case, we'd
want the web UI to consume a serialization of the _display-oriented_ plan
so that it doesn't need to re-implement all of these UI special cases.

This introduces to core a new diff action type for "refresh". Currently
this is used _only_ in the UI layer, to represent data source reads.
Later it would be good to use this type for the core diff as well, to
improve consistency, but that is left for another day to keep this change
focused on the UI.
This commit is contained in:
Martin Atkins 2017-08-23 16:23:02 -07:00
parent 4750f0607d
commit 3ea159297c
6 changed files with 752 additions and 271 deletions

View File

@ -96,28 +96,16 @@ func (b *Local) opApply(
return return
} }
trivialPlan := plan.Diff == nil || plan.Diff.Empty() dispPlan := format.NewPlan(plan)
trivialPlan := dispPlan.Empty()
hasUI := op.UIOut != nil && op.UIIn != nil hasUI := op.UIOut != nil && op.UIIn != nil
if hasUI && ((op.Destroy && !op.DestroyForce) || mustConfirm := hasUI && ((op.Destroy && !op.DestroyForce) || (!op.Destroy && !op.AutoApprove && !trivialPlan))
(!op.Destroy && !op.AutoApprove && !trivialPlan)) { if mustConfirm {
var desc, query string var desc, query string
if op.Destroy { if op.Destroy {
// Default destroy message // Default destroy message
desc = "Terraform will delete all your managed infrastructure, as shown above.\n" + desc = "Terraform will destroy all your managed infrastructure, as shown above.\n" +
"There is no undo. Only 'yes' will be accepted to confirm." "There is no undo. Only 'yes' will be accepted to confirm."
// If targets are specified, list those to user
if op.Targets != nil {
var descBuffer bytes.Buffer
descBuffer.WriteString("Terraform will delete the following infrastructure:\n")
for _, target := range op.Targets {
descBuffer.WriteString("\t")
descBuffer.WriteString(target)
descBuffer.WriteString("\n")
}
descBuffer.WriteString("There is no undo. Only 'yes' will be accepted to confirm")
desc = descBuffer.String()
}
query = "Do you really want to destroy?" query = "Do you really want to destroy?"
} else { } else {
desc = "Terraform will apply the changes described above.\n" + desc = "Terraform will apply the changes described above.\n" +
@ -132,11 +120,7 @@ func (b *Local) opApply(
} else { } else {
op.UIOut.Output("\n" + strings.TrimSpace(approvePlanHeader) + "\n") op.UIOut.Output("\n" + strings.TrimSpace(approvePlanHeader) + "\n")
} }
op.UIOut.Output(format.Plan(&format.PlanOpts{ op.UIOut.Output(dispPlan.Format(b.Colorize()))
Plan: plan,
Color: b.Colorize(),
ModuleDepth: -1,
}))
} }
v, err := op.UIIn.Input(&terraform.InputOpts{ v, err := op.UIIn.Input(&terraform.InputOpts{

View File

@ -133,7 +133,8 @@ func (b *Local) opPlan(
// Perform some output tasks if we have a CLI to output to. // Perform some output tasks if we have a CLI to output to.
if b.CLI != nil { if b.CLI != nil {
if plan.Diff.Empty() { dispPlan := format.NewPlan(plan)
if dispPlan.Empty() {
b.CLI.Output(b.Colorize().Color(strings.TrimSpace(planNoChanges))) b.CLI.Output(b.Colorize().Color(strings.TrimSpace(planNoChanges)))
return return
} }
@ -146,18 +147,14 @@ func (b *Local) opPlan(
path)) path))
} }
b.CLI.Output(format.Plan(&format.PlanOpts{ b.CLI.Output(dispPlan.Format(b.Colorize()))
Plan: plan,
Color: b.Colorize(),
ModuleDepth: -1,
}))
stats := dispPlan.Stats()
b.CLI.Output(b.Colorize().Color(fmt.Sprintf( b.CLI.Output(b.Colorize().Color(fmt.Sprintf(
"[reset][bold]Plan:[reset] "+ "[reset][bold]Plan:[reset] "+
"%d to add, %d to change, %d to destroy.", "%d to add, %d to change, %d to destroy.",
countHook.ToAdd+countHook.ToRemoveAndAdd, stats.ToAdd, stats.ToChange, stats.ToDestroy,
countHook.ToChange, )))
countHook.ToRemove+countHook.ToRemoveAndAdd)))
} }
} }

View File

@ -11,86 +11,225 @@ import (
"github.com/mitchellh/colorstring" "github.com/mitchellh/colorstring"
) )
// PlanOpts are the options for formatting a plan. // Plan is a representation of a plan optimized for display to
type PlanOpts struct { // an end-user, as opposed to terraform.Plan which is for internal use.
// Plan is the plan to format. This is required. //
Plan *terraform.Plan // DisplayPlan excludes implementation details that may otherwise appear
// in the main plan, such as destroy actions on data sources (which are
// Color is the colorizer. This is optional. // there only to clean up the state).
Color *colorstring.Colorize type Plan struct {
Resources []*InstanceDiff
// ModuleDepth is the depth of the modules to expand. By default this
// is zero which will not expand modules at all.
ModuleDepth int
} }
// Plan takes a plan and returns a // InstanceDiff is a representation of an instance diff optimized
func Plan(opts *PlanOpts) string { // for display, in conjunction with DisplayPlan.
p := opts.Plan type InstanceDiff struct {
if p.Diff == nil || p.Diff.Empty() { Addr *terraform.ResourceAddress
Action terraform.DiffChangeType
// Attributes describes changes to the attributes of the instance.
//
// For destroy diffs this is always nil.
Attributes []*AttributeDiff
Tainted bool
Deposed bool
}
// AttributeDiff is a representation of an attribute diff optimized
// for display, in conjunction with DisplayInstanceDiff.
type AttributeDiff struct {
// Path is a dot-delimited traversal through possibly many levels of list and map structure,
// intended for display purposes only.
Path string
Action terraform.DiffChangeType
OldValue string
NewValue string
NewComputed bool
Sensitive bool
ForcesNew bool
}
// PlanStats gives summary counts for a Plan.
type PlanStats struct {
ToAdd, ToChange, ToDestroy int
}
// NewPlan produces a display-oriented Plan from a terraform.Plan.
func NewPlan(plan *terraform.Plan) *Plan {
ret := &Plan{}
if plan == nil || plan.Diff == nil || plan.Diff.Empty() {
// Nothing to do!
return ret
}
for _, m := range plan.Diff.Modules {
var modulePath []string
if !m.IsRoot() {
// trim off the leading "root" path segment, since it's implied
// when we use a path in a resource address.
modulePath = m.Path[1:]
}
for k, r := range m.Resources {
if r.Empty() {
continue
}
addr, err := terraform.ParseResourceAddressForInstanceDiff(modulePath, k)
if err != nil {
// should never happen; indicates invalid diff
panic("invalid resource address in diff")
}
dataSource := addr.Mode == config.DataResourceMode
// We create "destroy" actions for data resources so we can clean
// up their entries in state, but this is an implementation detail
// that users shouldn't see.
if dataSource && r.ChangeType() == terraform.DiffDestroy {
continue
}
did := &InstanceDiff{
Addr: addr,
Action: r.ChangeType(),
Tainted: r.DestroyTainted,
Deposed: r.DestroyDeposed,
}
if dataSource && did.Action == terraform.DiffCreate {
// Use "refresh" as the action for display, since core
// currently uses Create for this.
did.Action = terraform.DiffRefresh
}
ret.Resources = append(ret.Resources, did)
if did.Action == terraform.DiffDestroy {
// Don't show any outputs for destroy actions
continue
}
for k, a := range r.Attributes {
var action terraform.DiffChangeType
switch {
case a.NewRemoved:
action = terraform.DiffDestroy
case did.Action == terraform.DiffCreate:
action = terraform.DiffCreate
default:
action = terraform.DiffUpdate
}
did.Attributes = append(did.Attributes, &AttributeDiff{
Path: k,
Action: action,
OldValue: a.Old,
NewValue: a.New,
Sensitive: a.Sensitive,
ForcesNew: a.RequiresNew,
NewComputed: a.NewComputed,
})
}
// Sort the attributes by their paths for display
sort.Slice(did.Attributes, func(i, j int) bool {
iPath := did.Attributes[i].Path
jPath := did.Attributes[j].Path
// as a special case, "id" is always first
switch {
case iPath != jPath && (iPath == "id" || jPath == "id"):
return iPath == "id"
default:
return iPath < jPath
}
})
}
}
// Sort the instance diffs by their addresses for display.
sort.Slice(ret.Resources, func(i, j int) bool {
iAddr := ret.Resources[i].Addr
jAddr := ret.Resources[j].Addr
return iAddr.Less(jAddr)
})
return ret
}
// Format produces and returns a text representation of the receiving plan
// intended for display in a terminal.
//
// If color is not nil, it is used to colorize the output.
func (p *Plan) Format(color *colorstring.Colorize) string {
if p.Empty() {
return "This plan does nothing." return "This plan does nothing."
} }
if opts.Color == nil { if color == nil {
opts.Color = &colorstring.Colorize{ color = &colorstring.Colorize{
Colors: colorstring.DefaultColors, Colors: colorstring.DefaultColors,
Reset: false, Reset: false,
} }
} }
buf := new(bytes.Buffer) // Find the longest path length of all the paths that are changing,
for _, m := range p.Diff.Modules { // so we can align them all.
if len(m.Path)-1 <= opts.ModuleDepth || opts.ModuleDepth == -1 { keyLen := 0
formatPlanModuleExpand(buf, m, opts) for _, r := range p.Resources {
} else { for _, attr := range r.Attributes {
formatPlanModuleSingle(buf, m, opts) key := attr.Path
if len(key) > keyLen {
keyLen = len(key)
} }
} }
}
buf := new(bytes.Buffer)
for _, r := range p.Resources {
formatPlanInstanceDiff(buf, r, keyLen, color)
}
return strings.TrimSpace(buf.String()) return strings.TrimSpace(buf.String())
} }
// formatPlanModuleExpand will output the given module and all of its // Stats returns statistics about the plan
// resources. func (p *Plan) Stats() PlanStats {
func formatPlanModuleExpand( var ret PlanStats
buf *bytes.Buffer, m *terraform.ModuleDiff, opts *PlanOpts) { for _, r := range p.Resources {
// Ignore empty diffs switch r.Action {
if m.Empty() { case terraform.DiffCreate:
return ret.ToAdd++
case terraform.DiffUpdate:
ret.ToChange++
case terraform.DiffDestroyCreate:
ret.ToAdd++
ret.ToDestroy++
case terraform.DiffDestroy:
ret.ToDestroy++
} }
}
return ret
}
var modulePath []string // Empty returns true if there is at least one resource diff in the receiving plan.
if !m.IsRoot() { func (p *Plan) Empty() bool {
modulePath = m.Path[1:] return len(p.Resources) == 0
} }
// We want to output the resources in sorted order to make things // formatPlanInstanceDiff writes the text representation of the given instance diff
// easier to scan through, so get all the resource names and sort them. // to the given buffer, using the given colorizer.
names := make([]string, 0, len(m.Resources)) func formatPlanInstanceDiff(buf *bytes.Buffer, r *InstanceDiff, keyLen int, colorizer *colorstring.Colorize) {
addrs := map[string]*terraform.ResourceAddress{} addrStr := r.Addr.String()
for name := range m.Resources {
names = append(names, name)
var err error
addrs[name], err = terraform.ParseResourceAddressForInstanceDiff(modulePath, name)
if err != nil {
// should never happen; indicates invalid diff
panic("invalid resource address in diff")
}
}
sort.Slice(names, func(i, j int) bool {
return addrs[names[i]].Less(addrs[names[j]])
})
// Go through each sorted name and start building the output
for _, name := range names {
rdiff := m.Resources[name]
if rdiff.Empty() {
continue
}
addr := addrs[name]
addrStr := addr.String()
dataSource := addr.Mode == config.DataResourceMode
// Determine the color for the text (green for adding, yellow // Determine the color for the text (green for adding, yellow
// for change, red for delete), and symbol, and output the // for change, red for delete), and symbol, and output the
@ -98,7 +237,7 @@ func formatPlanModuleExpand(
color := "yellow" color := "yellow"
symbol := " ~" symbol := " ~"
oldValues := true oldValues := true
switch rdiff.ChangeType() { switch r.Action {
case terraform.DiffDestroyCreate: case terraform.DiffDestroyCreate:
color = "yellow" color = "yellow"
symbol = "[red]-[reset]/[green]+[reset][yellow]" symbol = "[red]-[reset]/[green]+[reset][yellow]"
@ -106,137 +245,81 @@ func formatPlanModuleExpand(
color = "green" color = "green"
symbol = " +" symbol = " +"
oldValues = false oldValues = false
// If we're "creating" a data resource then we'll present it
// to the user as a "read" operation, so it's clear that this
// operation won't change anything outside of the Terraform state.
// Unfortunately by the time we get here we only have the name
// to work with, so we need to cheat and exploit knowledge of the
// naming scheme for data resources.
if dataSource {
symbol = " <="
color = "cyan"
}
case terraform.DiffDestroy: case terraform.DiffDestroy:
color = "red" color = "red"
symbol = " -" symbol = " -"
case terraform.DiffRefresh:
symbol = " <="
color = "cyan"
oldValues = false
} }
var extraAttr []string
if rdiff.DestroyTainted {
extraAttr = append(extraAttr, "tainted")
}
if rdiff.DestroyDeposed {
extraAttr = append(extraAttr, "deposed")
}
var extraStr string var extraStr string
if len(extraAttr) > 0 { if r.Tainted {
extraStr = fmt.Sprintf(" (%s)", strings.Join(extraAttr, ", ")) extraStr = extraStr + colorizer.Color(" (tainted)")
} }
if rdiff.ChangeType() == terraform.DiffDestroyCreate { if r.Deposed {
extraStr = extraStr + opts.Color.Color(" [red][bold](new resource required)") extraStr = extraStr + colorizer.Color(" (deposed)")
}
if r.Action == terraform.DiffDestroyCreate {
extraStr = extraStr + colorizer.Color(" [red][bold](new resource required)")
} }
buf.WriteString(opts.Color.Color(fmt.Sprintf( buf.WriteString(
colorizer.Color(fmt.Sprintf(
"[%s]%s %s%s\n", "[%s]%s %s%s\n",
color, symbol, addrStr, extraStr))) color, symbol, addrStr, extraStr,
)),
)
// Get all the attributes that are changing, and sort them. Also for _, attr := range r.Attributes {
// determine the longest key so that we can align them all.
keyLen := 0
keys := make([]string, 0, len(rdiff.Attributes))
for key, _ := range rdiff.Attributes {
// Skip the ID since we do that specially
if key == "id" {
continue
}
keys = append(keys, key) v := attr.NewValue
if len(key) > keyLen { var dispV string
keyLen = len(key) switch {
} case v == "" && attr.NewComputed:
} dispV = "<computed>"
sort.Strings(keys) case attr.Sensitive:
dispV = "<sensitive>"
// Go through and output each attribute default:
for _, attrK := range keys { dispV = fmt.Sprintf("%q", v)
attrDiff := rdiff.Attributes[attrK]
v := attrDiff.New
if v == "" && attrDiff.NewComputed {
v = "<computed>"
}
if attrDiff.Sensitive {
v = "<sensitive>"
} }
updateMsg := "" updateMsg := ""
if attrDiff.RequiresNew && rdiff.Destroy { switch {
updateMsg = opts.Color.Color(" [red](forces new resource)") case attr.ForcesNew && r.Action == terraform.DiffDestroy:
} else if attrDiff.Sensitive && oldValues { updateMsg = colorizer.Color(" [red](forces new resource)")
updateMsg = opts.Color.Color(" [yellow](attribute changed)") case attr.Sensitive && oldValues:
updateMsg = colorizer.Color(" [yellow](attribute changed)")
} }
if oldValues { if oldValues {
var u string u := attr.OldValue
if attrDiff.Sensitive { var dispU string
u = "<sensitive>" switch {
} else { case attr.Sensitive:
u = attrDiff.Old dispU = "<sensitive>"
default:
dispU = fmt.Sprintf("%q", u)
} }
buf.WriteString(fmt.Sprintf( buf.WriteString(fmt.Sprintf(
" %s:%s %#v => %#v%s\n", " %s:%s %s => %s%s\n",
attrK, attr.Path,
strings.Repeat(" ", keyLen-len(attrK)), strings.Repeat(" ", keyLen-len(attr.Path)),
u, dispU, dispV,
v, updateMsg,
updateMsg)) ))
} else { } else {
buf.WriteString(fmt.Sprintf( buf.WriteString(fmt.Sprintf(
" %s:%s %#v%s\n", " %s:%s %s%s\n",
attrK, attr.Path,
strings.Repeat(" ", keyLen-len(attrK)), strings.Repeat(" ", keyLen-len(attr.Path)),
v, dispV,
updateMsg)) updateMsg,
))
} }
} }
// Write the reset color so we don't overload the user's terminal // Write the reset color so we don't bleed color into later text
buf.WriteString(opts.Color.Color("[reset]\n")) buf.WriteString(colorizer.Color("[reset]\n"))
}
}
// formatPlanModuleSingle will output the given module and all of its
// resources.
func formatPlanModuleSingle(
buf *bytes.Buffer, m *terraform.ModuleDiff, opts *PlanOpts) {
// Ignore empty diffs
if m.Empty() {
return
}
moduleName := fmt.Sprintf("module.%s", strings.Join(m.Path[1:], "."))
// Determine the color for the text (green for adding, yellow
// for change, red for delete), and symbol, and output the
// resource header.
color := "yellow"
symbol := "~"
switch m.ChangeType() {
case terraform.DiffCreate:
color = "green"
symbol = "+"
case terraform.DiffDestroy:
color = "red"
symbol = "-"
}
buf.WriteString(opts.Color.Color(fmt.Sprintf(
"[%s]%s %s\n",
color, symbol, moduleName)))
buf.WriteString(fmt.Sprintf(
" %d resource(s)",
len(m.Resources)))
buf.WriteString(opts.Color.Color("[reset]\n"))
} }

View File

@ -1,14 +1,452 @@
package format package format
import ( import (
"reflect"
"strings" "strings"
"testing" "testing"
"github.com/davecgh/go-spew/spew"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/colorstring" "github.com/mitchellh/colorstring"
) )
// Test that a root level data source gets a special plan output on create var disabledColorize = &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
}
func TestNewPlan(t *testing.T) {
tests := map[string]struct {
Input *terraform.Plan
Want *Plan
}{
"nil input": {
Input: nil,
Want: &Plan{
Resources: nil,
},
},
"nil diff": {
Input: &terraform.Plan{},
Want: &Plan{
Resources: nil,
},
},
"empty diff": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{},
},
},
},
},
Want: &Plan{
Resources: nil,
},
},
"create managed resource": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{
"test_resource.foo": {
Attributes: map[string]*terraform.ResourceAttrDiff{
"id": {
NewComputed: true,
RequiresNew: true,
},
},
},
},
},
},
},
},
Want: &Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffCreate,
Attributes: []*AttributeDiff{
{
Path: "id",
Action: terraform.DiffCreate,
NewComputed: true,
ForcesNew: true,
},
},
},
},
},
},
"create managed resource in child module": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{
"test_resource.foo": {
Attributes: map[string]*terraform.ResourceAttrDiff{
"id": {
NewComputed: true,
RequiresNew: true,
},
},
},
},
},
{
Path: []string{"root", "foo"},
Resources: map[string]*terraform.InstanceDiff{
"test_resource.foo": {
Attributes: map[string]*terraform.ResourceAttrDiff{
"id": {
NewComputed: true,
RequiresNew: true,
},
},
},
},
},
},
},
},
Want: &Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffCreate,
Attributes: []*AttributeDiff{
{
Path: "id",
Action: terraform.DiffCreate,
NewComputed: true,
ForcesNew: true,
},
},
},
{
Addr: mustParseResourceAddress("module.foo.test_resource.foo"),
Action: terraform.DiffCreate,
Attributes: []*AttributeDiff{
{
Path: "id",
Action: terraform.DiffCreate,
NewComputed: true,
ForcesNew: true,
},
},
},
},
},
},
"create data resource": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{
"data.test_data_source.foo": {
Attributes: map[string]*terraform.ResourceAttrDiff{
"id": {
NewComputed: true,
RequiresNew: true,
},
},
},
},
},
},
},
},
Want: &Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("data.test_data_source.foo"),
Action: terraform.DiffRefresh,
Attributes: []*AttributeDiff{
{
Path: "id",
Action: terraform.DiffUpdate,
NewComputed: true,
ForcesNew: true,
},
},
},
},
},
},
"destroy managed resource": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{
"test_resource.foo": {
Destroy: true,
},
},
},
},
},
},
Want: &Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffDestroy,
},
},
},
},
"destroy data resource": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{
"data.test_data_source.foo": {
Destroy: true,
},
},
},
},
},
},
Want: &Plan{
// Data source destroys are not shown
Resources: nil,
},
},
"destroy many instances of a resource": {
Input: &terraform.Plan{
Diff: &terraform.Diff{
Modules: []*terraform.ModuleDiff{
{
Path: []string{"root"},
Resources: map[string]*terraform.InstanceDiff{
"test_resource.foo.0": {
Destroy: true,
},
"test_resource.foo.1": {
Destroy: true,
},
"test_resource.foo.10": {
Destroy: true,
},
"test_resource.foo.2": {
Destroy: true,
},
"test_resource.foo.3": {
Destroy: true,
},
"test_resource.foo.4": {
Destroy: true,
},
"test_resource.foo.5": {
Destroy: true,
},
"test_resource.foo.6": {
Destroy: true,
},
"test_resource.foo.7": {
Destroy: true,
},
"test_resource.foo.8": {
Destroy: true,
},
"test_resource.foo.9": {
Destroy: true,
},
},
},
},
},
},
Want: &Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo[0]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[1]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[2]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[3]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[4]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[5]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[6]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[7]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[8]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[9]"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.foo[10]"),
Action: terraform.DiffDestroy,
},
},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
got := NewPlan(test.Input)
if !reflect.DeepEqual(got, test.Want) {
t.Errorf(
"wrong result\ninput: %sgot: %swant:%s",
spew.Sdump(test.Input),
spew.Sdump(got),
spew.Sdump(test.Want),
)
}
})
}
}
func TestPlanStats(t *testing.T) {
tests := map[string]struct {
Input *Plan
Want PlanStats
}{
"empty": {
&Plan{},
PlanStats{},
},
"destroy": {
&Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffDestroy,
},
{
Addr: mustParseResourceAddress("test_resource.bar"),
Action: terraform.DiffDestroy,
},
},
},
PlanStats{
ToDestroy: 2,
},
},
"create": {
&Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffCreate,
},
{
Addr: mustParseResourceAddress("test_resource.bar"),
Action: terraform.DiffCreate,
},
},
},
PlanStats{
ToAdd: 2,
},
},
"update": {
&Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffUpdate,
},
{
Addr: mustParseResourceAddress("test_resource.bar"),
Action: terraform.DiffUpdate,
},
},
},
PlanStats{
ToChange: 2,
},
},
"data source refresh": {
&Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("data.test.foo"),
Action: terraform.DiffRefresh,
},
},
},
PlanStats{
// data resource refreshes are not counted in our stats
},
},
"replace": {
&Plan{
Resources: []*InstanceDiff{
{
Addr: mustParseResourceAddress("test_resource.foo"),
Action: terraform.DiffDestroyCreate,
},
{
Addr: mustParseResourceAddress("test_resource.bar"),
Action: terraform.DiffDestroyCreate,
},
},
},
PlanStats{
ToDestroy: 2,
ToAdd: 2,
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
got := test.Input.Stats()
if !reflect.DeepEqual(got, test.Want) {
t.Errorf(
"wrong result\ninput: %sgot: %swant:%s",
spew.Sdump(test.Input),
spew.Sdump(got),
spew.Sdump(test.Want),
)
}
})
}
}
// Test that deposed instances are marked as such
func TestPlan_destroyDeposed(t *testing.T) { func TestPlan_destroyDeposed(t *testing.T) {
plan := &terraform.Plan{ plan := &terraform.Plan{
Diff: &terraform.Diff{ Diff: &terraform.Diff{
@ -24,16 +462,8 @@ func TestPlan_destroyDeposed(t *testing.T) {
}, },
}, },
} }
opts := &PlanOpts{ dispPlan := NewPlan(plan)
Plan: plan, actual := dispPlan.Format(disabledColorize)
Color: &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
},
ModuleDepth: 1,
}
actual := Plan(opts)
expected := strings.TrimSpace(` expected := strings.TrimSpace(`
- aws_instance.foo (deposed) - aws_instance.foo (deposed)
@ -64,16 +494,8 @@ func TestPlan_displayInterpolations(t *testing.T) {
}, },
}, },
} }
opts := &PlanOpts{ dispPlan := NewPlan(plan)
Plan: plan, out := dispPlan.Format(disabledColorize)
Color: &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
},
ModuleDepth: 1,
}
out := Plan(opts)
lines := strings.Split(out, "\n") lines := strings.Split(out, "\n")
if len(lines) != 2 { if len(lines) != 2 {
t.Fatal("expected 2 lines of output, got:\n", out) t.Fatal("expected 2 lines of output, got:\n", out)
@ -108,16 +530,8 @@ func TestPlan_rootDataSource(t *testing.T) {
}, },
}, },
} }
opts := &PlanOpts{ dispPlan := NewPlan(plan)
Plan: plan, actual := dispPlan.Format(disabledColorize)
Color: &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
},
ModuleDepth: 1,
}
actual := Plan(opts)
expected := strings.TrimSpace(` expected := strings.TrimSpace(`
<= data.type.name <= data.type.name
@ -149,16 +563,8 @@ func TestPlan_nestedDataSource(t *testing.T) {
}, },
}, },
} }
opts := &PlanOpts{ dispPlan := NewPlan(plan)
Plan: plan, actual := dispPlan.Format(disabledColorize)
Color: &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
},
ModuleDepth: 2,
}
actual := Plan(opts)
expected := strings.TrimSpace(` expected := strings.TrimSpace(`
<= module.nested.data.type.name <= module.nested.data.type.name
@ -168,3 +574,11 @@ func TestPlan_nestedDataSource(t *testing.T) {
t.Fatalf("expected:\n\n%s\n\ngot:\n\n%s", expected, actual) t.Fatalf("expected:\n\n%s\n\ngot:\n\n%s", expected, actual)
} }
} }
func mustParseResourceAddress(s string) *terraform.ResourceAddress {
addr, err := terraform.ParseResourceAddress(s)
if err != nil {
panic(err)
}
return addr
}

View File

@ -110,11 +110,8 @@ func (c *ShowCommand) Run(args []string) int {
} }
if plan != nil { if plan != nil {
c.Ui.Output(format.Plan(&format.PlanOpts{ dispPlan := format.NewPlan(plan)
Plan: plan, c.Ui.Output(dispPlan.Format(c.Colorize()))
Color: c.Colorize(),
ModuleDepth: moduleDepth,
}))
return 0 return 0
} }

View File

@ -23,6 +23,12 @@ const (
DiffUpdate DiffUpdate
DiffDestroy DiffDestroy
DiffDestroyCreate DiffDestroyCreate
// DiffRefresh is only used in the UI for displaying diffs.
// Managed resource reads never appear in plan, and when data source
// reads appear they are represented as DiffCreate in core before
// transforming to DiffRefresh in the UI layer.
DiffRefresh // TODO: Actually use DiffRefresh in core too, for less confusion
) )
// multiVal matches the index key to a flatmapped set, list or map // multiVal matches the index key to a flatmapped set, list or map