github.com/pulumi/terraform@v1.4.0/pkg/backend/local/backend_plan.go (about)

     1  package local
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/pulumi/terraform/pkg/backend"
     9  	"github.com/pulumi/terraform/pkg/logging"
    10  	"github.com/pulumi/terraform/pkg/plans"
    11  	"github.com/pulumi/terraform/pkg/plans/planfile"
    12  	"github.com/pulumi/terraform/pkg/states/statefile"
    13  	"github.com/pulumi/terraform/pkg/states/statemgr"
    14  	"github.com/pulumi/terraform/pkg/terraform"
    15  	"github.com/pulumi/terraform/pkg/tfdiags"
    16  )
    17  
    18  func (b *Local) opPlan(
    19  	stopCtx context.Context,
    20  	cancelCtx context.Context,
    21  	op *backend.Operation,
    22  	runningOp *backend.RunningOperation) {
    23  
    24  	log.Printf("[INFO] backend/local: starting Plan operation")
    25  
    26  	var diags tfdiags.Diagnostics
    27  
    28  	if op.PlanFile != nil {
    29  		diags = diags.Append(tfdiags.Sourceless(
    30  			tfdiags.Error,
    31  			"Can't re-plan a saved plan",
    32  			"The plan command was given a saved plan file as its input. This command generates "+
    33  				"a new plan, and so it requires a configuration directory as its argument.",
    34  		))
    35  		op.ReportResult(runningOp, diags)
    36  		return
    37  	}
    38  
    39  	// Local planning requires a config, unless we're planning to destroy.
    40  	if op.PlanMode != plans.DestroyMode && !op.HasConfig() {
    41  		diags = diags.Append(tfdiags.Sourceless(
    42  			tfdiags.Error,
    43  			"No configuration files",
    44  			"Plan requires configuration to be present. Planning without a configuration would "+
    45  				"mark everything for destruction, which is normally not what is desired. If you "+
    46  				"would like to destroy everything, run plan with the -destroy option. Otherwise, "+
    47  				"create a Terraform configuration file (.tf file) and try again.",
    48  		))
    49  		op.ReportResult(runningOp, diags)
    50  		return
    51  	}
    52  
    53  	if b.ContextOpts == nil {
    54  		b.ContextOpts = new(terraform.ContextOpts)
    55  	}
    56  
    57  	// Get our context
    58  	lr, configSnap, opState, ctxDiags := b.localRun(op)
    59  	diags = diags.Append(ctxDiags)
    60  	if ctxDiags.HasErrors() {
    61  		op.ReportResult(runningOp, diags)
    62  		return
    63  	}
    64  	// the state was locked during succesfull context creation; unlock the state
    65  	// when the operation completes
    66  	defer func() {
    67  		diags := op.StateLocker.Unlock()
    68  		if diags.HasErrors() {
    69  			op.View.Diagnostics(diags)
    70  			runningOp.Result = backend.OperationFailure
    71  		}
    72  	}()
    73  
    74  	// Since planning doesn't immediately change the persisted state, the
    75  	// resulting state is always just the input state.
    76  	runningOp.State = lr.InputState
    77  
    78  	// Perform the plan in a goroutine so we can be interrupted
    79  	var plan *plans.Plan
    80  	var planDiags tfdiags.Diagnostics
    81  	doneCh := make(chan struct{})
    82  	go func() {
    83  		defer logging.PanicHandler()
    84  		defer close(doneCh)
    85  		log.Printf("[INFO] backend/local: plan calling Plan")
    86  		plan, planDiags = lr.Core.Plan(lr.Config, lr.InputState, lr.PlanOpts)
    87  	}()
    88  
    89  	if b.opWait(doneCh, stopCtx, cancelCtx, lr.Core, opState, op.View) {
    90  		// If we get in here then the operation was cancelled, which is always
    91  		// considered to be a failure.
    92  		log.Printf("[INFO] backend/local: plan operation was force-cancelled by interrupt")
    93  		runningOp.Result = backend.OperationFailure
    94  		return
    95  	}
    96  	log.Printf("[INFO] backend/local: plan operation completed")
    97  
    98  	// NOTE: We intentionally don't stop here on errors because we always want
    99  	// to try to present a partial plan report and, if the user chose to,
   100  	// generate a partial saved plan file for external analysis.
   101  	diags = diags.Append(planDiags)
   102  
   103  	// Record whether this plan includes any side-effects that could be applied.
   104  	runningOp.PlanEmpty = !plan.CanApply()
   105  
   106  	// Save the plan to disk
   107  	if path := op.PlanOutPath; path != "" && plan != nil {
   108  		if op.PlanOutBackend == nil {
   109  			// This is always a bug in the operation caller; it's not valid
   110  			// to set PlanOutPath without also setting PlanOutBackend.
   111  			diags = diags.Append(fmt.Errorf(
   112  				"PlanOutPath set without also setting PlanOutBackend (this is a bug in Terraform)"),
   113  			)
   114  			op.ReportResult(runningOp, diags)
   115  			return
   116  		}
   117  		plan.Backend = *op.PlanOutBackend
   118  
   119  		// We may have updated the state in the refresh step above, but we
   120  		// will freeze that updated state in the plan file for now and
   121  		// only write it if this plan is subsequently applied.
   122  		plannedStateFile := statemgr.PlannedStateUpdate(opState, plan.PriorState)
   123  
   124  		// We also include a file containing the state as it existed before
   125  		// we took any action at all, but this one isn't intended to ever
   126  		// be saved to the backend (an equivalent snapshot should already be
   127  		// there) and so we just use a stub state file header in this case.
   128  		// NOTE: This won't be exactly identical to the latest state snapshot
   129  		// in the backend because it's still been subject to state upgrading
   130  		// to make it consumable by the current Terraform version, and
   131  		// intentionally doesn't preserve the header info.
   132  		prevStateFile := &statefile.File{
   133  			State: plan.PrevRunState,
   134  		}
   135  
   136  		log.Printf("[INFO] backend/local: writing plan output to: %s", path)
   137  		err := planfile.Create(path, planfile.CreateArgs{
   138  			ConfigSnapshot:       configSnap,
   139  			PreviousRunStateFile: prevStateFile,
   140  			StateFile:            plannedStateFile,
   141  			Plan:                 plan,
   142  			DependencyLocks:      op.DependencyLocks,
   143  		})
   144  		if err != nil {
   145  			diags = diags.Append(tfdiags.Sourceless(
   146  				tfdiags.Error,
   147  				"Failed to write plan file",
   148  				fmt.Sprintf("The plan file could not be written: %s.", err),
   149  			))
   150  			op.ReportResult(runningOp, diags)
   151  			return
   152  		}
   153  	}
   154  
   155  	// Render the plan, if we produced one.
   156  	// (This might potentially be a partial plan with Errored set to true)
   157  	if plan != nil {
   158  		schemas, moreDiags := lr.Core.Schemas(lr.Config, lr.InputState)
   159  		diags = diags.Append(moreDiags)
   160  		if moreDiags.HasErrors() {
   161  			op.ReportResult(runningOp, diags)
   162  			return
   163  		}
   164  		op.View.Plan(plan, schemas)
   165  	}
   166  
   167  	// If we've accumulated any diagnostics along the way then we'll show them
   168  	// here just before we show the summary and next steps. This can potentially
   169  	// include errors, because we intentionally try to show a partial plan
   170  	// above even if Terraform Core encountered an error partway through
   171  	// creating it.
   172  	op.ReportResult(runningOp, diags)
   173  
   174  	if !runningOp.PlanEmpty {
   175  		op.View.PlanNextStep(op.PlanOutPath)
   176  	}
   177  }