Lesson 2 of 7 in Infrastructure as Code with Terraform and OpenTofu
The workflow: init, plan, apply, destroy
Every Terraform/OpenTofu run follows the same loop: init downloads the plugins, plan shows what would change, apply makes the change, and destroy removes what the configuration created. The plan is a preview you read before anything happens.
Draft. This lesson is written and waiting for a person to run every command and review it. It is safe to learn from, but check the official documentation for anything you depend on.
Read these first: What Infrastructure as Code means
The problem this solves
Changing real infrastructure is risky because a small edit can delete something important. You need a way to see the effect of an edit before it happens.
The plan step gives you that. The tool compares your files with what it recorded earlier and with what exists now, then prints exactly what it would create, change or remove. Nothing changes until you approve.
How it works
- Control
- Runs code
- Other
- Data
The command line reads your config files, uses a provider plugin to talk to the real target, and records the result in a state file.
- Config files to terraform / tofu: reads
- terraform / tofu to Provider plugin: calls
- Provider plugin to Real target: creates or changes
- terraform / tofu to State: records
- People and clients
- Control
- Runs code
- Data
You write config, init downloads providers, plan previews the change, apply makes it and the result is saved to state.
- Write to init: 1 download plugins
- init to plan: 2 compare
- plan to apply: 3 you approve
- apply to State: 4 save result
The configuration is written in HCL (HashiCorp Configuration Language), a small language for blocks and arguments. A resource block says one thing should exist, for example a file. Its type, such as local_file, tells the tool which provider handles it.
init looks at which providers your files need and downloads them into a hidden .terraform folder. It also writes .terraform.lock.hcl, which pins the exact provider versions so teammates get the same ones. You commit that lock file.
plan builds a list of actions. In its output a + means create, - means destroy, ~ means change in place, and -/+ means destroy and create again, which the plan marks with the words forces replacement. Read the final summary line first, then read any - lines carefully.
apply runs the plan after you type yes, and destroy is a plan that removes everything the configuration manages.
Try it yourself
This uses the free local and random providers. They create a text file and a random name on your laptop. Init needs internet access to download the providers, nothing else.
- 1Write a configuration
mkdir -p ~/iac-lab/workflow && cd ~/iac-lab/workflow cat > main.tf <<"EOF" terraform { required_providers { local = { source = "hashicorp/local" } random = { source = "hashicorp/random" } } } resource "random_pet" "name" { length = 2 } resource "local_file" "greeting" { filename = "greeting.txt" content = format("Hello from %s", random_pet.name.id) } EOFTwo resources. The file's content refers to the pet name, so Terraform/OpenTofu knows it must create the name first.
- 2Initialise and validate
terraform init terraform validate
You should see
Success! The configuration is valid.
init prints a message saying it was successfully initialized. With OpenTofu use
tofuin place ofterraformin every command. Nothing exists yet. - 3Preview the change
terraform plan
Expect two resources marked with
+and a last line ofPlan: 2 to add, 0 to change, 0 to destroy.Some values show as(known after apply)because they do not exist yet. - 4Apply it
terraform apply cat greeting.txt; echo
Type
yeswhen asked. The summary should sayApply complete! Resources: 2 added, 0 changed, 0 destroyed.and the file contains Hello from followed by a random two-word name. - 5Run plan again with no edits
terraform plan
Expect
No changes. Your infrastructure matches the configuration.This is idempotence in action. - 6Change something, then clean up
sed -i.bak 's/length = 2/length = 3/' main.tf terraform plan terraform destroy
The plan shows the random name being replaced (
-/+) and the file updated, because the file depends on the name. Typeyesat destroy to remove both.sed -i.bakworks on Linux and macOS.
What breaks, and where to look
Error: Inconsistent dependency lock file, or Error: Failed to query available provider packages.
- WHY IT HAPPENS
- init was never run in this folder, the provider could not be downloaded (no internet, proxy, firewall), or the provider name in
required_providersis misspelled. - CHECK FIRST
- Run
terraform initagain and read the first error line. Check thesourceaddress, for examplehashicorp/local, and your network.
The plan says something will be destroyed or replaced that you did not expect.
- WHY IT HAPPENS
- Some arguments cannot be changed on an existing object, so the tool must delete and recreate it. The plan marks this with
forces replacement. - CHECK FIRST
- Search the plan output for
forces replacementandmust be replaced, find which argument caused it, and decide if recreation is acceptable before you type yes.
You applied and later cannot remember what changed.
- WHY IT HAPPENS
- Apply was run without reading or saving the plan, so there is no record of the intended change.
- CHECK FIRST
- Use
terraform plan -out=tfplan, review it, thenterraform apply tfplanso the apply runs exactly what you reviewed.
When not to use this
- A plan only knows what the provider reports. It cannot warn you about application-level damage, such as a database losing data when its server is replaced.
- Applying straight from a laptop is fine for learning. For shared infrastructure, teams usually run plan and apply from a pipeline so everyone follows the same steps.
Check yourself
What does init do and what file does it write that you should commit?
It downloads providers and modules. It writes .terraform.lock.hcl, which pins provider versions and should be committed.
What does -/+ in a plan mean?
The object will be destroyed and created again, which the plan flags as forces replacement.
Why is a second plan with no edits a useful check?
It should report no changes. If it does not, something differs between the files, the state and the real target.
Keep going
Lesson 64 of 92 in the DevOps path