github.com/cycloidio/terraform@v1.1.10-0.20220513142504-76d5c768dc63/terraform/context_apply.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/cycloidio/terraform/addrs"
     8  	"github.com/cycloidio/terraform/configs"
     9  	"github.com/cycloidio/terraform/plans"
    10  	"github.com/cycloidio/terraform/states"
    11  	"github.com/cycloidio/terraform/tfdiags"
    12  	"github.com/zclconf/go-cty/cty"
    13  )
    14  
    15  // Apply performs the actions described by the given Plan object and returns
    16  // the resulting updated state.
    17  //
    18  // The given configuration *must* be the same configuration that was passed
    19  // earlier to Context.Plan in order to create this plan.
    20  //
    21  // Even if the returned diagnostics contains errors, Apply always returns the
    22  // resulting state which is likely to have been partially-updated.
    23  func (c *Context) Apply(plan *plans.Plan, config *configs.Config) (*states.State, tfdiags.Diagnostics) {
    24  	defer c.acquireRun("apply")()
    25  
    26  	log.Printf("[DEBUG] Building and walking apply graph for %s plan", plan.UIMode)
    27  
    28  	graph, operation, diags := c.applyGraph(plan, config, true)
    29  	if diags.HasErrors() {
    30  		return nil, diags
    31  	}
    32  
    33  	variables := InputValues{}
    34  	for name, dyVal := range plan.VariableValues {
    35  		val, err := dyVal.Decode(cty.DynamicPseudoType)
    36  		if err != nil {
    37  			diags = diags.Append(tfdiags.Sourceless(
    38  				tfdiags.Error,
    39  				"Invalid variable value in plan",
    40  				fmt.Sprintf("Invalid value for variable %q recorded in plan file: %s.", name, err),
    41  			))
    42  			continue
    43  		}
    44  
    45  		variables[name] = &InputValue{
    46  			Value:      val,
    47  			SourceType: ValueFromPlan,
    48  		}
    49  	}
    50  
    51  	workingState := plan.PriorState.DeepCopy()
    52  	walker, walkDiags := c.walk(graph, operation, &graphWalkOpts{
    53  		Config:             config,
    54  		InputState:         workingState,
    55  		Changes:            plan.Changes,
    56  		RootVariableValues: variables,
    57  	})
    58  	diags = diags.Append(walker.NonFatalDiagnostics)
    59  	diags = diags.Append(walkDiags)
    60  
    61  	newState := walker.State.Close()
    62  	if plan.UIMode == plans.DestroyMode && !diags.HasErrors() {
    63  		// NOTE: This is a vestigial violation of the rule that we mustn't
    64  		// use plan.UIMode to affect apply-time behavior.
    65  		// We ideally ought to just call newState.PruneResourceHusks
    66  		// unconditionally here, but we historically didn't and haven't yet
    67  		// verified that it'd be safe to do so.
    68  		newState.PruneResourceHusks()
    69  	}
    70  
    71  	if len(plan.TargetAddrs) > 0 {
    72  		diags = diags.Append(tfdiags.Sourceless(
    73  			tfdiags.Warning,
    74  			"Applied changes may be incomplete",
    75  			`The plan was created with the -target option in effect, so some changes requested in the configuration may have been ignored and the output values may not be fully updated. Run the following command to verify that no other changes are pending:
    76      terraform plan
    77  	
    78  Note that the -target option is not suitable for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when Terraform specifically suggests to use it as part of an error message.`,
    79  		))
    80  	}
    81  
    82  	return newState, diags
    83  }
    84  
    85  func (c *Context) applyGraph(plan *plans.Plan, config *configs.Config, validate bool) (*Graph, walkOperation, tfdiags.Diagnostics) {
    86  	graph, diags := (&ApplyGraphBuilder{
    87  		Config:       config,
    88  		Changes:      plan.Changes,
    89  		State:        plan.PriorState,
    90  		Plugins:      c.plugins,
    91  		Targets:      plan.TargetAddrs,
    92  		ForceReplace: plan.ForceReplaceAddrs,
    93  		Validate:     validate,
    94  	}).Build(addrs.RootModuleInstance)
    95  
    96  	operation := walkApply
    97  	if plan.UIMode == plans.DestroyMode {
    98  		// NOTE: This is a vestigial violation of the rule that we mustn't
    99  		// use plan.UIMode to affect apply-time behavior. It's a design error
   100  		// if anything downstream switches behavior when operation is set
   101  		// to walkDestroy, but we've not yet fully audited that.
   102  		// TODO: Audit that and remove walkDestroy as an operation mode.
   103  		operation = walkDestroy
   104  	}
   105  
   106  	return graph, operation, diags
   107  }
   108  
   109  // ApplyGraphForUI is a last vestage of graphs in the public interface of
   110  // Context (as opposed to graphs as an implementation detail) intended only for
   111  // use by the "terraform graph" command when asked to render an apply-time
   112  // graph.
   113  //
   114  // The result of this is intended only for rendering ot the user as a dot
   115  // graph, and so may change in future in order to make the result more useful
   116  // in that context, even if drifts away from the physical graph that Terraform
   117  // Core currently uses as an implementation detail of planning.
   118  func (c *Context) ApplyGraphForUI(plan *plans.Plan, config *configs.Config) (*Graph, tfdiags.Diagnostics) {
   119  	// For now though, this really is just the internal graph, confusing
   120  	// implementation details and all.
   121  
   122  	var diags tfdiags.Diagnostics
   123  
   124  	graph, _, moreDiags := c.applyGraph(plan, config, false)
   125  	diags = diags.Append(moreDiags)
   126  	return graph, diags
   127  }