github.com/hugorut/terraform@v1.1.3/website/docs/internals/lifecycle.mdx (about) 1 --- 2 page_title: Resource Lifecycle 3 description: >- 4 Resources have a strict lifecycle, and can be thought of as basic state 5 machines. Understanding this lifecycle can help better understand how 6 Terraform generates an execution plan, how it safely executes that plan, and 7 what the resource provider is doing throughout all of this. 8 --- 9 10 # Resource Lifecycle 11 12 Resources have a strict lifecycle, and can be thought of as basic 13 state machines. Understanding this lifecycle can help better understand 14 how Terraform generates an execution plan, how it safely executes that 15 plan, and what the resource provider is doing throughout all of this. 16 17 ~> **Advanced Topic!** This page covers technical details 18 of Terraform. You don't need to understand these details to 19 effectively use Terraform. The details are documented here for 20 those who wish to learn about them without having to go 21 spelunking through the source code. 22 23 ## Lifecycle 24 25 A resource roughly follows the steps below: 26 27 1. `ValidateResource` is called to do a high-level structural 28 validation of a resource's configuration. The configuration 29 at this point is raw and the interpolations have not been processed. 30 The value of any key is not guaranteed and is just meant to be 31 a quick structural check. 32 33 1. `Diff` is called with the current state and the configuration. 34 The resource provider inspects this and returns a diff, outlining 35 all the changes that need to occur to the resource. The diff includes 36 details such as whether or not the resource is being destroyed, what 37 attribute necessitates the destroy, old values and new values, whether 38 a value is computed, etc. It is up to the resource provider to 39 have this knowledge. 40 41 1. `Apply` is called with the current state and the diff. Apply does 42 not have access to the configuration. This is a safety mechanism 43 that limits the possibility that a provider changes a diff on the 44 fly. `Apply` must apply a diff as prescribed and do nothing else 45 to remain true to the Terraform execution plan. Apply returns the 46 new state of the resource (or nil if the resource was destroyed). 47 48 1. If a resource was just created and did not exist before, and the 49 apply succeeded without error, then the provisioners are executed 50 in sequence. If any provisioner errors, the resource is marked as 51 _tainted_, so that it will be destroyed on the next apply. 52 53 ## Partial State and Error Handling 54 55 If an error happens at any stage in the lifecycle of a resource, 56 Terraform stores a partial state of the resource. This behavior is 57 critical for Terraform to ensure that you don't end up with any 58 _zombie_ resources: resources that were created by Terraform but 59 no longer managed by Terraform due to a loss of state.