Skip to main content
Welcome to this hands-on lab on defining and using variables in Terraform (OpenTofu). By the end of this tutorial, you’ll understand how to declare different variable types, fetch elements from maps and lists, and refactor resources to leverage variables for cleaner, reusable configurations.

1. Variable Type Quiz

Question: Which of the following is not a valid Terraform variable type?
  • object
  • item
  • tuple
  • list
  • map
Answer: item is not a valid variable type in Terraform/OpenTofu. For more details, see the Terraform Variable Types.

2. Data Type Quiz

Question: Which of the following is not a valid data type in OpenTofu?
  • list
  • tuple
  • map
  • array
  • set
Answer: array is not a valid data type in OpenTofu.

Setup: Navigate to the Variables Directory


3. Inspecting number

Open variables.tf and locate:
Question: Which type does number belong to?
Answer: It’s a boolean.

4. Fetching a Map Value

In variables.tf, you have:
Question: How do you retrieve the "slow" entry?
You can also use the dot notation if your key is a valid identifier, e.g., var.hard_drive.slow.

5. List Indexing

Definition in variables.tf:
  • Lists are zero-indexed.
  • "Male" → index 0
  • "Female" → index 1
Answer: The index of "Female" is 1.

6. Identifying a Set Definition Error

  • Type: set(string)
  • Mistake: Sets must not contain duplicates; "jerry" appears twice.
Defining duplicate elements in a set will cause validation errors. Ensure each member is unique.

7. Inspecting a Resource Block

In main.tf, you added:
Question: What is the value of the content argument?
Answer: "phanius"

8. Refactoring to Use Variables

  1. Declare a map variable in variables.tf:
  2. Update the resource in main.tf:
This makes your configuration more modular and easier to maintain.

9. Initialize, Plan, and Apply

Expected output snapshot:
Apply the changes:
After success:
Verify the file:

That’s it for this lab. Thank you for following along!

Watch Video

Practice Lab