6 min read

The Lifecycle of a Terraform Resource.

The Lifecycle of a Terraform Resource.

Behind the show and bluster of being likely the most well known IaC tool in the world right now, Terraform is remarkably simple. For lack of a better description, its a state machine (i.e. it takes a resource through all the stages of a typical Create Read Update Delete or CRUD).

Table of Contents

  1. Lifecycle Function Hooks
  2. Demo: Resource Lifecycle
    1. Terraform's main.tf
    2. terraform init
    3. terraform plan
    4. terraform apply
    5. Update the content of our resource
    6. Delete resource

Lifecycle Function Hooks

Terraform resources implement what is called a Resource Schema Interface (RSI). Think of the RSI as a checklist of things that each Terraform resource MUST do if it is to be provisioned through it.

Plugin Development - Terraform Plugin Protocol | Terraform | HashiCorp  Developer
Figure 1: A RSI for Terraform Resources Image taken from here.

The RSI above maps out the list of events/checks/requirements that each Terraform resource should be wary of. Failure to complete any of these could result in an error.

The RSI requires Terraform resources to define hooks for CRUD functions (one each for Create, Read, Update, and Delete).

Depending upon conditions, Terraform will call these hooks to achieve the following outcomes:

  • Create is called during resource creation
  • Read during plan generation
  • Update during resource updates
  • Delete during deletes

Demo: Resource Lifecycle

For this demo, we will use a local resource provider (as opposed to using AWS, Azure, or GCP like is typically done).

📢
For a list of all Terraform Providers, visit this link.

Before we proceed, let's make sure that the folder we are working in empty.

Figure 1: The working folder is empty, right now !

Step 1: Create Terraform main.tf file

Figure 2: A simple Terraform configuration file.
💡
Since we have declared local as our choice of required provider for provisioning, Terraform will not require a provider section. Though if interested, you can add a section for provider as shown:
provider "local" {}

Step 2: Initialize your Terraform workspace.

Terraform is not aware it has anything to configure/provision ... yet.

We have to use

terraform init

to initialize the workspace (= folder in which Terraform files are kept) and also let Terraform Engine something is expected of it.

Figure 3: terraform init is the first command issued.

terraform init creates a set of folders inside the workspace.

Figure 4: Initialization generates a set of hidden folders.

Step 3: Generate Terraform's plan for provisioning the resource.

The next stage is

terraform plan
Figure 5: terraform plan will list all the steps Terraform will take to provision the file.

Terraform will list all the resources, along with details for it, as an output from the planning step.

Question: But what happens behind the scene as Terraform plans its execution?

Answer: A lot. Terraform will check the resources being asked for and the provider to use in creating them. It, then, goes through either a Create(), an Update() or a Delete().

Figure 6: terraform plan goes through a number of checks to confirm which resources need to be updated, created, deleted or left alone.

Additionally, we can save the output of terraform plan to a json file if needed.

Terraform has a feature that can output the steps planned into a json file.

terraform plan -out plan.out
terraform show -json plan.out > plan.json
cat plan.json

Step 4: Use terraform apply to put the plan into action.

Figure 7: terraform apply will confirm your desire to go ahead before kicking off the provisioning of the text file called 'story'.

Step 5: Check the outputs of terraform plan in the folder.

Figure 8: terraform apply created the resource we asked for (teentitans.txt) but also another file that we did not see earlier, the terraform.state file.

Let's confirm the contents of teentitans.txt first.

Figure 9: The resource (local file) was created and we confirmed its content were what we expected it to be.

But what is this terraform.tfstate file?

Its an extremely important file and documents the state of various resources that have been provisioned. As shown in Figure 6, Terraform will take a peek inside the terraform.tfstate to check which resources exist.

We should take a look inside the terraform.tfstate file:

Figure 10: The contents of the terraform.tfstate show the resources that were created along with the configuration details for the resources.
Avoid editing or deleting with the terraform.tfstate file. Terraform will lose track of the resources it manages.

So what really happens behind the scene when terraform apply is invoked?

Simple answer is, of course, it will create a text file named teentitan.txt but this is covering over the real magic.

Terraform will call the Create () hook and then using the local_file provider, complete the creation and saving of teentitan.txt.

Step 6: Update the resource.

To demonstrate Terrform's behavior when we update existing resources, we can edit the main.tf file and add a line or two of additional text to it. This additional text will be added to the content of the file.

Figure 11: Adding more text to the file to demonstrate the Update () hook.

Terraform will go through the state check as it did when the file was created for the first time, but from that point on, the sequence changes completely.

Figure 12: The active path shows an update being implemented.

To kickstart the updating flow, use

terraform plan

and the resulting output shows what Terraform thinks you want to achieve.

Figure 13: Since this is an update, state will be refreshed. Additionally the -/+ indicates the file will be deleted first and then recreated. Note: The delete/create is not a typical process for most updates.

To complete the process, use

terraform apply -auto-approve
📢
The -auto-approve switch bypasses the explicit entering of 'Yes' before Terraform begins its work.

Finally, we can check the contents of the teentitan.txt file using

cat teentitan.txt

Step 6: Delete resource.

The text file has outlived its usefulness. Our dislike for Teen Titans has resulted in the show being taken off screen and therefore, we can get rid of the resources we created to help achieve this outcome.

The command to delete the resource is

terraform destroy -auto-approve

Terraform will again consult with the terraform.tfstate file, get information about the resource(s) we are about to delete and then proceed on with its job.

Figure 14: The Delete flow starts off like Create or Update but has different outcomes.

I write to remember and if in the process, I can help someone learn about Containers, Orchestration (Docker Compose, Kubernetes), GitOps, DevSecOps, VR/AR, Architecture, and Data Management, that is just icing on the cake.