Working with Terraform / Lesson 2 of 2
Variables, Outputs and Modules
Make configurations reusable: parameterise them, expose results, and package them as modules.
8 min Intermediate 7 steps
IN THIS LESSON
Step 1 of 7
STEP 1 / 7
Variables make code reusable
Hard-coded values tie a configuration to one situation. Input variables turn those values into parameters, so the same code can be used with different settings.
variable "instance_type" {
type = string
default = "t3.micro"
}
resource "aws_instance" "web" {
instance_type = var.instance_type
}← → step · R replay · Space play/pause
YOU'LL LEARN
- How input variables make code reusable
- How to set different values per environment
- How outputs share results
- How modules package and reuse resources
- Variables make code reusable. Hard-coded values tie a configuration to one situation. Input variables turn those values into parameters, so the same code can be used with different settings.
- Set values per environment. Supply values at run time without changing the code. A .tfvars file is a convenient way to keep a set of values per environment.
- Outputs expose results. Outputs publish values from your configuration, such as an IP address or an ID. They are printed after apply and are how one module hands results to another.
- Modules package resources. A module is a folder of Terraform files that you call like a function. It groups resources that belong together, such as a whole network, behind a small set of inputs and outputs.
- Reuse it for every environment. Call the same module once per environment with different inputs. Each call creates its own copy of the resources, so dev and prod stay consistent without copy and paste.
- Use registry modules. You do not have to write every module yourself. The Terraform Registry hosts public modules for common setups. Pin a version so an upstream change cannot surprise you.
- Recap. Variables, outputs and modules are how a single configuration grows into a maintainable code base.