chapter two

2 Lifecycle of a Terraform Resource

 

This chapter covers:

  • Generating and applying execution plans
  • Analyzing when function hooks are triggered by Terraform
  • Utilizing the Local provider to create and manage files
  • Simulating, detecting, and correcting for configuration drift
  • Understanding the basics of Terraform state management

When you do away with all its bells and whistles, Terraform is a surprisingly simple technology. Fundamentally, Terraform is a glorified state management tool that performs CRUD operations (create, read, update, delete) on managed resources. Oftentimes managed resources will be cloud-based resources, but they don’t have to be. Anything that implements CRUD can be represented as a Terraform resource, so long as there is sufficient desire and motivation to do so.

In this chapter we will deep-dive into the internals of Terraform by walking through the lifecycle of a single resource. We could use any resource for this task, but to keep things simple, we’ll use a resource that doesn’t call any remote network APIs. These special sorts of resources are called local-only resources and only exist within the confines of Terraform, or the machine running Terraform. Local-only resources typically serve a marginal purpose, such as to glue together “real” infrastructure objects, but they also make a great teaching aid. Examples of local-only resources include private keys, self-signed TLS certificates, and random ids.

2.1      Process Overview

2.1.1   Lifecycle Function Hooks

2.2      Declaring a Local File Resource

2.3      Initializing the Workspace

2.4      Generating an Execution Plan

2.4.1   Inspecting the Plan

2.5      Creating the Local File Resource

2.6      Performing No-Op

2.7      Updating the Local File Resource

2.7.1   Detecting Configuration Drift

2.7.2   Terraform Refresh

2.8      Deleting the Local File Resource

2.9      Summary