CD3: Terraform foundations

Lesson 2 of 5 · reading 15–25 minutes; practice and project time is on the module page

Resources, variables, outputs and references

🎯You'll be able to

Read and write Terraform's language: resources, references between them, input variables with validation, locals, outputs and count.

🏠The everyday picture

A recipe for a family-size biryani says "rice: 2 cups per 4 people". The number of people is the input; the quantities follow from it. Change one number and the whole recipe adjusts, without rewriting it.

📘What it really is

📝A worked example

Input: add the app_count variable above and change the app resource to count = var.app_count, with name = "${local.prefix}-app-${count.index}". Run terraform plan -var app_count=3.

Expected output: the plan shows docker_container.app[0], [1] and [2]. Running terraform plan -var app_count=9 fails before planning with app_count must be between 1 and 8. That validation protects you from a typo that would start 90 copies.

🌍Where it's used

📝Case scenario

A media company's Terraform had the number of video servers written in six places. During a cricket final, an engineer raised it in five of them; the sixth, in a load balancer rule, kept sending traffic to only the old servers. After the match they replaced the six numbers with one variable referenced everywhere, so one change updated all of them.

🖱️Try it

Run terraform console in infra/ and type local.prefix, then var.env, then upper(local.prefix), then exit. Success: you can evaluate expressions against your configuration without changing anything.

⚠️Common mistakes

🛠️For your project

Project 1 adds the app_version and app_count variables and the app_containers and app_version outputs, which the pipeline and the autoscaler read.

✅Quick check

How does Terraform know to create the volume before the container?

Show the answer

The container refers to the volume, and Terraform orders work from those references.

How do you set a variable without editing a file?

Show the answer

-var name=value, or an environment variable TF_VAR_name.

← PreviousWhy infrastructure as code, and how Terraform works
ProLearners Assist