Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 40 min · revision 3

Lab: plan, apply and destroy, then extract a reusable module

Write a small reusable module with typed, validated variables and outputs, call it twice from a root configuration with a pinned provider, and run the whole lifecycle: init, lock file, plan, apply, a clean second plan, state, a validation failure and destroy.

Contentsand lesson path

What you will learn

  • Explain declarative provisioning, the plan and apply cycle and the role of state, and contrast it with configuration management tools such as Ansible.
  • Write a configuration with providers, resources, variables, outputs and a reusable module, with provider versions pinned in a lock file.

01. Goal and setup

In lesson 1 you declared one local_file resource. Real teams need the same piece of infrastructure several times, once per environment, with small differences. Copying the block and editing it invites mistakes, so they write it once as a module: a folder of .tf files that takes input variables and returns outputs, like a function with parameters and a return value. The configuration that calls modules is the root module.

You will write a module that renders a JSON service configuration file, call it for dev and staging, and run the full lifecycle on your own machine. The hashicorp/local provider manages files on disk, so you need no cloud account and pay nothing; the commands, plan output and state are the same ones you will use with a cloud provider.

You need: OpenTofu 1.6 or later (this lab was run with OpenTofu 1.13.9) and network access for the first init. Terraform 1.6 or later works too: type terraform wherever the lab says tofu; the lab was also run with Terraform 1.17.2, and the messages say "Terraform" instead of "OpenTofu". Run everything from an empty folder called iac-lab.

Lab folder at the end of step 2
iac-lab/
├── .gitignore
├── main.tf                  root module: provider pin and two module calls
├── outputs.tf               values the root module prints
└── modules/
    └── web-service-config/  the reusable module
        ├── variables.tf     inputs, with types and validation
        ├── main.tf          the resource it manages
        └── outputs.tf       what callers may read

02. Step 1: Write the module

Start with the inputs. Each variable has a type, so a caller who passes the text "eighty" for a number gets an error instead of a broken file. A default makes an input optional. A validation block adds a rule of your own; if its condition is false, OpenTofu stops with your error_message before it changes anything.

HCL · modules/web-service-config/variables.tf
variable "environment" {
  description = "Deployment environment name"
  type        = string

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging or prod."
  }
}

variable "service_port" {
  description = "TCP port the service listens on"
  type        = number
  default     = 8080

  validation {
    condition     = var.service_port >= 1024 && var.service_port <= 65535
    error_message = "service_port must be between 1024 and 65535."
  }
}

variable "config_path" {
  description = "Where to write the rendered JSON configuration"
  type        = string
}

The resource reads its values through var.<name>. The module says which provider it needs (source) but not which version: the root module pins versions once for the whole configuration.

HCL · modules/web-service-config/main.tf
terraform {
  required_providers {
    local = {
      source = "hashicorp/local"
    }
  }
}

resource "local_file" "config" {
  filename             = var.config_path
  file_permission      = "0644"
  directory_permission = "0755"
  content = jsonencode({
    environment = var.environment
    port        = var.service_port
  })
}

Outputs are the module's public interface. From outside, the caller can read only what is declared here, as module.<call name>.<output name>. The resources inside stay private, which lets you change the module's internals without breaking its callers.

HCL · modules/web-service-config/outputs.tf
output "config_path" {
  description = "Path of the rendered configuration file"
  value       = local_file.config.filename
}

output "config_file_id" {
  description = "SHA-1 of the file content, which local_file uses as its ID"
  value       = local_file.config.id
}

03. Step 2: Write the root configuration

required_providers names the provider and a version constraint: ~> 2.9 allows 2.9 and any later 2.x release, but not 3.0, which could contain breaking changes. The two module blocks use the same source with different inputs; web_dev leaves out service_port, so it gets the default 8080. ${path.root} is the folder of the root module, so the files land inside the lab folder and you need no root rights.

HCL · main.tf
terraform {
  required_version = ">= 1.6.0"
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
  }
}

# The same module, called twice with different inputs
module "web_dev" {
  source = "./modules/web-service-config"

  environment = "dev"
  config_path = "${path.root}/out/dev/service.json"
}

module "web_staging" {
  source = "./modules/web-service-config"

  environment  = "staging"
  service_port = 8443
  config_path  = "${path.root}/out/staging/service.json"
}
HCL · outputs.tf
output "config_files" {
  description = "Rendered file per environment"
  value = {
    dev     = module.web_dev.config_path
    staging = module.web_staging.config_path
  }
}

output "staging_config_id" {
  description = "Changes whenever the staging file content changes"
  value       = module.web_staging.config_file_id
}
Text · .gitignore
.terraform/
*.tfstate
*.tfstate.*
tfplan

04. Step 3: Initialise and commit the lock file

Terminal
tofu init
head -7 .terraform.lock.hcl
git add .gitignore .terraform.lock.hcl *.tf modules   # in a Git repository
Expected output of init, then of head (abridged at each …)
Initializing the backend...
Initializing modules...
- web_dev in modules/web-service-config
- web_staging in modules/web-service-config

Initializing provider plugins...
- Finding hashicorp/local versions matching "~> 2.9"...
- Installing hashicorp/local v2.9.1...
- Installed hashicorp/local v2.9.1 (signed, key ID 0C0AF313E5FD9F80)
…
OpenTofu has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that OpenTofu can guarantee to make the same selections by default when
you run "tofu init" in the future.

OpenTofu has been successfully initialized!
…
# This file is maintained automatically by "tofu init".
# Manual edits may be lost in future updates.

provider "registry.opentofu.org/hashicorp/local" {
  version     = "2.9.1"
  constraints = "~> 2.9"
  hashes = [

init downloads the provider into the hidden .terraform/ folder and writes .terraform.lock.hcl. The constraint in main.tf says which versions are allowed; the lock file records the exact version that was chosen (2.9.1) and checksums of the provider package. Commit the lock file, so that a teammate's init or a CI job selects the same version and rejects a download whose checksum does not match. Keep .terraform/ out of Git: it holds downloaded binaries for your operating system and other local data that init can recreate.

A later release that still matches ~> 2.9 is not picked up by itself. When you want it, run tofu init -upgrade, which selects the newest allowed version and rewrites the lock file, and review that change in a pull request like any code change. The lock file covers providers only; modules from a registry or Git are not locked, so pin those with an exact version or a Git tag (?ref=v1.4.0).

05. Step 4: Save a plan and read it

Terminal
tofu plan -out=tfplan
Expected output (the staging block, identical in shape to dev, abridged at …)
OpenTofu used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create

OpenTofu will perform the following actions:

  # module.web_dev.local_file.config will be created
  + resource "local_file" "config" {
      + content              = jsonencode(
            {
              + environment = "dev"
              + port        = 8080
            }
        )
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0755"
      + file_permission      = "0644"
      + filename             = "./out/dev/service.json"
      + id                   = (known after apply)
    }

  # module.web_staging.local_file.config will be created
  + resource "local_file" "config" {
      + content              = jsonencode(
            {
              + environment = "staging"
              + port        = 8443
            }
        )
      …
      + filename             = "./out/staging/service.json"
      + id                   = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + config_files      = {
      + dev     = "./out/dev/service.json"
      + staging = "./out/staging/service.json"
    }
  + staging_config_id = (known after apply)

─────────────────────────────────────────────────────────────────────────────

Saved the plan to: tfplan

To perform exactly these actions, run the following command to apply:
    tofu apply "tfplan"

Read a plan from the summary up: 2 to add, 0 to change, 0 to destroy is what you expected for a first run. Each resource address includes the module call, module.web_dev.local_file.config, so you can tell the two copies apart. + means create; later you will also see ~ (update in place), - (destroy) and -/+ (destroy, then create a replacement). (known after apply) marks values the provider computes only when it creates the object.

-out=tfplan saves the plan, and tofu apply tfplan then performs exactly those actions without planning again, which is how CI separates review from apply. If the state changes in between, for example because a teammate applied, OpenTofu refuses the file with Saved plan is stale and you plan again. Treat the file as a secret: it stores configuration and state values in clear text, including values marked sensitive that the terminal hides, unless you enable OpenTofu plan encryption. Keep it out of Git (it is in .gitignore) and delete it after use.

06. Step 5: Apply the saved plan

Terminal
tofu apply tfplan
cat out/dev/service.json; echo; cat out/staging/service.json; echo
Illustrative output (the Creating lines can come in another order; long lines wrapped)
module.web_staging.local_file.config: Creating...
module.web_dev.local_file.config: Creating...
module.web_staging.local_file.config: Creation complete after 0s
    [id=3e29a9b74cab56c35325b410d7b96dab0a273dd3]
module.web_dev.local_file.config: Creation complete after 0s
    [id=b0c4656fe5dd5412c89b3ed79c457e6fdede674a]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

config_files = {
  "dev" = "./out/dev/service.json"
  "staging" = "./out/staging/service.json"
}
staging_config_id = "3e29a9b74cab56c35325b410d7b96dab0a273dd3"
{"environment":"dev","port":8080}
{"environment":"staging","port":8443}

The two files have no dependency on each other, so OpenTofu creates them in parallel. jsonencode writes keys in sorted order without spaces, and the ID of a local_file is the SHA-1 of its content, so your IDs match these if your files do. OpenTofu has also written terraform.tfstate, which maps each address to the real file.

07. Step 6: Plan again and expect no changes

Terminal
tofu plan -detailed-exitcode; echo "exit code: $?"
Expected output (the two Refreshing lines can swap; long lines wrapped)
module.web_staging.local_file.config: Refreshing state...
    [id=3e29a9b74cab56c35325b410d7b96dab0a273dd3]
module.web_dev.local_file.config: Refreshing state...
    [id=b0c4656fe5dd5412c89b3ed79c457e6fdede674a]

No changes. Your infrastructure matches the configuration.
exit code: 0

Plan first refreshes: it reads each real object and compares it with the code. Nothing differs, so a second plan right after an apply is empty; that is the declarative cycle working. -detailed-exitcode turns the answer into an exit code a script can test: 0 means no changes, 2 means the plan succeeded and found changes, and 1 means an error. A scheduled CI job that alerts on exit code 2 is a simple drift detector.

08. Step 7: Inspect state and outputs

Terminal
tofu state list
tofu output -raw staging_config_id; echo
sha1sum out/staging/service.json        # macOS: shasum out/staging/service.json
echo 'module.web_staging.local_file.config.id' | tofu console
Expected output
module.web_dev.local_file.config
module.web_staging.local_file.config
3e29a9b74cab56c35325b410d7b96dab0a273dd3
3e29a9b74cab56c35325b410d7b96dab0a273dd3  out/staging/service.json
╷
│ Error: Unsupported attribute
│ 
│   on <console-input> line 1:
│   (source code not available)
│ 
│ This object does not have an attribute named "local_file".
╵

State lists one address per managed object. -raw prints an output without quotes, which is handy in scripts, and the value matches the checksum of the real file. The last command tries to reach inside the module from the root and fails: a caller can use module.web_staging.config_file_id, the declared output, but not the module's resources.

09. Step 8: Watch validation stop a bad input

Terminal · break the input, plan, then restore main.tf
sed -i.bak 's/= "staging"/= "production"/' main.tf
tofu plan; echo "exit code: $?"
mv main.tf.bak main.tf
Expected output
╷
│ Error: Invalid value for variable
│ 
│   on main.tf line 22, in module "web_staging":
│   22:   environment  = "production"
│     ├────────────────
│     │ var.environment is "production"
│ 
│ environment must be dev, staging or prod.
│ 
│ This was checked by the validation rule at
│ modules/web-service-config/variables.tf:5,3-13.
╵
exit code: 1

The plan fails before it refreshes or changes anything, and the message points at the caller's line and at the rule. That is the purpose of validation: the module author turns a mistake that would otherwise produce a wrong file, or a wrong cloud resource, into a clear error at plan time.

10. Step 9: See why instance keys matter

To create several copies of one resource, you can use count (copies numbered 0, 1, 2) or for_each (copies named by a key). Add this file, which creates one small file per zone both ways, and apply it. -auto-approve skips the confirmation prompt; it is acceptable here because the lab files are disposable. The plan uses -no-color: OpenTofu writes colour codes even into a pipe, and they would stop grep from matching the start of each line.

HCL · zones.tf
# Step 9: the same three files, addressed by position and by name
variable "zones" {
  type    = list(string)
  default = ["a", "b", "c"]
}

resource "local_file" "by_index" {
  count    = length(var.zones)
  filename = "${path.root}/out/count/${var.zones[count.index]}.txt"
  content  = var.zones[count.index]
}

resource "local_file" "by_key" {
  for_each = toset(var.zones)
  filename = "${path.root}/out/each/${each.key}.txt"
  content  = each.key
}
Terminal · apply, then plan with zone "a" removed
tofu apply -auto-approve > /dev/null
tofu plan -no-color -var 'zones=["b", "c"]' | grep -E '^  # |^Plan|forces'
Expected output (filename lines wrapped)
  # local_file.by_index[0] must be replaced
      ~ content              = "a" -> "b" # forces replacement
      ~ filename             = "./out/count/a.txt" -> "./out/count/b.txt"
          # forces replacement
  # local_file.by_index[1] must be replaced
      ~ content              = "b" -> "c" # forces replacement
      ~ filename             = "./out/count/b.txt" -> "./out/count/c.txt"
          # forces replacement
  # local_file.by_index[2] will be destroyed
  # (because index [2] is out of range for count)
  # local_file.by_key["a"] will be destroyed
  # (because key ["a"] is not in for_each map)
Plan: 2 to add, 0 to change, 4 to destroy.

With count, removing the first zone shifts every later item down one position: index 0 now means "b" and index 1 means "c", so both are replaced and index 2 is destroyed. With for_each, each copy is addressed by its key, so only by_key["a"] goes. For local files that is harmless; for subnets or disks, a replacement destroys a real object. Use for_each when the copies have names of their own. Do not apply this plan; the next step removes everything.

11. Step 10: Destroy everything

Terminal · type yes when asked
tofu destroy
tofu state list | wc -l
rm -f tfplan
Illustrative output (abridged at …; the Destroying lines come in any order)
Plan: 0 to add, 0 to change, 8 to destroy.
…
Do you really want to destroy all resources?
  OpenTofu will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value:
…
Destroy complete! Resources: 8 destroyed.
0

destroy is a plan in which every managed object is deleted, so it shows the list and waits for yes. It deletes only what is in state; anything created by hand stays. The empty folders under out/ remain because the provider manages the files, not the folders. Running destroy regularly in a test environment proves that your code can remove everything it created.

12. Check your understanding

Practice check · 3 questions

Validation, saved plans and plan exit codes

Three questions on variable validation, saved plans and scripted plan checks.

Q1. The module accepts `environment` only if it is dev, staging or prod. A caller passes "production". When does OpenTofu report it?
Q2. You save a plan with `tofu plan -out=tfplan`. A teammate then applies another change to the same state. What happens when you run `tofu apply tfplan`?
Q3. A nightly job runs `tofu plan -detailed-exitcode` against production and alerts unless the exit code is 0. Tonight it exits with 2. What does that tell you?
Practice only: not graded, not saved, not evidence.

13. Apply it

Find two blocks in a real configuration that differ only in a few values, and turn them into one module with typed variables, a validation rule and outputs. Then check your work against this list:

  • The root module pins every provider with a constraint, and .terraform.lock.hcl is committed; .terraform/, state and plan files are not.
  • Provider upgrades happen through tofu init -upgrade in a reviewed pull request.
  • Modules from Git or a registry are pinned to a tag or exact version.
  • Copies with names of their own use for_each, not count.
  • CI saves the plan, a person reviews it, and the job applies that file and then deletes it.

14. Review prompt

Without looking back, name the three files of a module and what each one is for, and say how a caller reads a value the module creates. Explain the difference between a version constraint and the lock file, and what init -upgrade changes. Describe what you expect from a second plan right after an apply, and what exit codes 0, 1 and 2 mean with -detailed-exitcode.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check