Bird
Raised Fist0
Terraformcloud~5 mins

Why variables make configurations reusable in Terraform - Why It Works

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
When you write infrastructure code, you want to use it many times without changing the main file. Variables help by letting you change values easily without rewriting the whole code. This saves time and reduces mistakes.
When you want to create the same infrastructure in different environments like testing and production with small changes.
When you need to share your infrastructure code with teammates who might use different settings.
When you want to avoid repeating the same values in many places in your code.
When you want to quickly update settings like server size or region without editing many files.
When you want to keep sensitive information like passwords separate from your main code.
Config File - main.tf
main.tf
variable "region" {
  description = "The cloud region to deploy resources"
  type        = string
  default     = "us-east-1"
}

variable "instance_type" {
  description = "Type of the compute instance"
  type        = string
  default     = "t2.micro"
}

provider "aws" {
  region = var.region
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.instance_type
  tags = {
    Name = "example-instance"
  }
}

This file defines two variables: region and instance_type. They let you change where and what kind of server you create without changing the main code.

The provider block uses the region variable to decide where to deploy.

The aws_instance resource uses the instance_type variable to set the server size.

Commands
This command sets up Terraform in the current folder. It downloads needed plugins and prepares to run your code.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized!
This command shows what Terraform will do before making any changes. It uses the variables with their default values.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_instance.example will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + tags = { + "Name" = "example-instance" } } Plan: 1 to add, 0 to change, 0 to destroy. ───────────────────────────────────────────────────────────────────────────── Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions will be performed if "terraform apply" is subsequently run.
This command creates the resources using the variables. The -auto-approve flag skips asking for confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example: Creating... aws_instance.example: Still creating... [10s elapsed] aws_instance.example: Creation complete after 15s [id=i-0abcd1234efgh5678] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
→
-auto-approve - Skip confirmation prompt before applying changes
This command deletes the created resources to clean up. The -auto-approve flag skips confirmation.
Terminal
terraform destroy -auto-approve
Expected OutputExpected
aws_instance.example: Destroying... aws_instance.example: Still destroying... [10s elapsed] aws_instance.example: Destruction complete after 12s Destroy complete! Resources: 1 destroyed.
→
-auto-approve - Skip confirmation prompt before destroying resources
Key Concept

If you remember nothing else from this pattern, remember: variables let you change important settings without rewriting your whole infrastructure code.

Common Mistakes
Hardcoding values directly in resource blocks instead of using variables
This makes the code less flexible and harder to reuse in different situations.
Define variables for values that might change and reference them in your resources.
Not providing default values for variables and not passing values when running Terraform
Terraform will ask for input every time or fail if it cannot get a value.
Either set sensible default values in the variable block or pass values using command line or files.
Using variables but forgetting to reference them with the correct syntax (var.variable_name)
Terraform will not recognize the variable and throw an error.
Always use var.variable_name to access variable values inside your configuration.
Summary
Use variables to make your Terraform code flexible and reusable.
Initialize Terraform with 'terraform init' before planning or applying.
Use 'terraform plan' to see what changes will happen with current variable values.
Apply changes with 'terraform apply' and clean up with 'terraform destroy'.

Practice

(1/5)
1. Why do variables make Terraform configurations reusable?
easy
A. Because they allow changing values without modifying the main code
B. Because they automatically create resources
C. Because they prevent any errors in the code
D. Because they remove the need for providers

Solution

  1. Step 1: Understand the role of variables

    Variables hold values that can be changed without editing the main configuration code.
  2. Step 2: Recognize how this affects reusability

    Changing variable values lets you reuse the same code for different setups or environments easily.
  3. Final Answer:

    Because they allow changing values without modifying the main code -> Option A
  4. Quick Check:

    Variables = flexible values [OK]
Hint: Variables let you change inputs, not code [OK]
Common Mistakes:
  • Thinking variables create resources automatically
  • Believing variables fix all code errors
  • Assuming variables replace providers
2. Which of the following is the correct way to declare a variable in Terraform?
easy
A. var region = "us-west-1"
B. variable "region" { default = "us-west-1" }
C. set variable region = "us-west-1"
D. define region: "us-west-1"

Solution

  1. Step 1: Recall Terraform variable syntax

    Terraform variables are declared using the keyword 'variable' followed by the name in quotes and a block with settings.
  2. Step 2: Match the syntax to options

    variable "region" { default = "us-west-1" } matches the correct syntax: variable "region" { default = "us-west-1" }.
  3. Final Answer:

    variable "region" { default = "us-west-1" } -> Option B
  4. Quick Check:

    Correct variable syntax = variable "region" { default = "us-west-1" } [OK]
Hint: Look for 'variable' keyword and braces {} [OK]
Common Mistakes:
  • Using 'var' keyword incorrectly
  • Missing braces {} around variable block
  • Using assignment syntax from other languages
3. Given this Terraform snippet:
variable "instance_type" { default = "t2.micro" }
resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = var.instance_type
}

What will be the instance type if no variable value is provided?
medium
A. t2.micro
B. ami-123456
C. var.instance_type
D. No instance type will be set

Solution

  1. Step 1: Identify the default variable value

    The variable "instance_type" has a default value set to "t2.micro".
  2. Step 2: Understand variable usage in resource

    The resource uses var.instance_type, so if no override is given, it uses the default "t2.micro".
  3. Final Answer:

    t2.micro -> Option A
  4. Quick Check:

    Default variable value used = t2.micro [OK]
Hint: Default value applies if no override given [OK]
Common Mistakes:
  • Confusing AMI ID with instance type
  • Thinking var.instance_type is a string literal
  • Assuming no value means no instance type
4. You wrote this variable declaration:
variable "env" = "production"

Why does Terraform give an error?
medium
A. Because default values must be numbers
B. Because variable names cannot be "env"
C. Because variable declarations need a block, not an assignment
D. Because variables cannot have default values

Solution

  1. Step 1: Check variable declaration syntax

    Terraform variables must be declared using a block: variable "name" { ... } not with '=' assignment.
  2. Step 2: Identify the error cause

    Using '=' directly after variable name causes syntax error.
  3. Final Answer:

    Because variable declarations need a block, not an assignment -> Option C
  4. Quick Check:

    Variable declaration requires block syntax [OK]
Hint: Use braces {} for variables, not '=' [OK]
Common Mistakes:
  • Using '=' instead of block for variables
  • Thinking variable names are restricted
  • Believing default values must be numeric
5. You want to reuse a Terraform module for multiple environments (dev, test, prod) with different instance sizes. How do variables help achieve this?
hard
A. By writing separate code for each environment without variables
B. By using variables only for provider configuration
C. By hardcoding instance sizes inside the module
D. By defining a variable for instance size and passing different values per environment

Solution

  1. Step 1: Understand module reuse with variables

    Variables let you set inputs like instance size dynamically when calling the module.
  2. Step 2: Apply different values per environment

    Passing different values for the instance size variable lets the same module create resources tailored to each environment.
  3. Final Answer:

    By defining a variable for instance size and passing different values per environment -> Option D
  4. Quick Check:

    Variables enable flexible module inputs [OK]
Hint: Use variables to customize modules per environment [OK]
Common Mistakes:
  • Duplicating code instead of using variables
  • Hardcoding values inside modules
  • Limiting variables to provider settings only