github.com/hashicorp/terraform-plugin-sdk@v1.17.2/terraform/eval_check_prevent_destroy.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/hashicorp/terraform-plugin-sdk/internal/plans"
     7  
     8  	"github.com/hashicorp/hcl/v2"
     9  
    10  	"github.com/hashicorp/terraform-plugin-sdk/internal/addrs"
    11  	"github.com/hashicorp/terraform-plugin-sdk/internal/configs"
    12  	"github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags"
    13  )
    14  
    15  // EvalPreventDestroy is an EvalNode implementation that returns an
    16  // error if a resource has PreventDestroy configured and the diff
    17  // would destroy the resource.
    18  type EvalCheckPreventDestroy struct {
    19  	Addr   addrs.ResourceInstance
    20  	Config *configs.Resource
    21  	Change **plans.ResourceInstanceChange
    22  }
    23  
    24  func (n *EvalCheckPreventDestroy) Eval(ctx EvalContext) (interface{}, error) {
    25  	if n.Change == nil || *n.Change == nil || n.Config == nil || n.Config.Managed == nil {
    26  		return nil, nil
    27  	}
    28  
    29  	change := *n.Change
    30  	preventDestroy := n.Config.Managed.PreventDestroy
    31  
    32  	if (change.Action == plans.Delete || change.Action.IsReplace()) && preventDestroy {
    33  		var diags tfdiags.Diagnostics
    34  		diags = diags.Append(&hcl.Diagnostic{
    35  			Severity: hcl.DiagError,
    36  			Summary:  "Instance cannot be destroyed",
    37  			Detail: fmt.Sprintf(
    38  				"Resource %s has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. To avoid this error and continue with the plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using the -target flag.",
    39  				n.Addr.Absolute(ctx.Path()).String(),
    40  			),
    41  			Subject: &n.Config.DeclRange,
    42  		})
    43  		return nil, diags.Err()
    44  	}
    45  
    46  	return nil, nil
    47  }