Variables and Outputs: Making Infrastructure Reusable

My journey from copy-paste chaos to parameterized infrastructure elegance


Table of Contents


Introduction: The Copy-Paste Nightmare

It was month two of using Terraform, and I had a problem. I needed to create identical infrastructure for three environments: development, staging, and production. My solution? Copy-paste the entire configuration three times.

Then disaster struck. I found a bug in the database configuration. Now I had to fix it three times. I missed one. Production broke. Post-mortem meeting. Awkward conversations.

That's when I learned about variables. Instead of copy-paste, I could write the configuration once and parameterize the differences:

Variables transformed my Terraform code from brittle copy-paste hell to elegant, reusable infrastructure as code. This article is about making your infrastructure parameterized, flexible, and maintainable.


What Are Variables?

Variables in Terraform are named values that allow you to parameterize your configurations. They make your code:

  • Reusable - Same code, different values

  • Maintainable - Change once, apply everywhere

  • Flexible - Easy to customize per environment

  • Testable - Override values for testing

  • Documented - Self-documenting configuration options

Variables vs Hardcoding

Without Variables (Bad):

With Variables (Good):

Variable Flow

spinner

Variable Types and Declarations

Terraform supports several variable types, each with specific use cases.

Basic Variable Types

1. String

2. Number

3. Boolean

Collection Types

4. List

5. Set (like list but no duplicates, no order)

6. Map

7. Object (structured type)

8. Tuple (list with specific types)

Complex Nested Types


Input Variables Deep Dive

Let's explore all aspects of input variable declarations.

Complete Variable Declaration

Variable Without Default (Required)

Using Variables


Variable Files (.tfvars)

Variable files let you organize variable values separately from configuration.

File Structure

variables.tf - Declarations

terraform.tfvars - Default values (auto-loaded)

production.tfvars - Production values

Using Variable Files

Variable File Formats

HCL format (.tfvars):

JSON format (.tfvars.json):


Variable Validation

Validation rules ensure variables meet requirements before Terraform runs.

Basic Validation

Invalid value:

Error:

Complex Validation Examples

String Length:

Regex Pattern:

Number Range:

List Validation:

Object Validation:

Multiple Conditions:


Sensitive Variables

Sensitive variables hide their values in logs and output.

Marking Variables as Sensitive

Sensitive Variable Behavior

Without sensitive = true:

Output:

With sensitive = true:

Output:

Working with Sensitive Values

Providing Sensitive Variables

Environment variables (recommended):

Variable file (encrypted):

Never do this:


Variable Precedence

When multiple sources provide values for the same variable, Terraform uses a precedence order.

Precedence Order (Lowest to Highest)

spinner

Precedence Example

variables.tf:

terraform.tfvars:

production.auto.tfvars:

Command line:


Understanding Outputs

Outputs expose values from your Terraform configuration. They're useful for:

  • Displaying important information after deployment

  • Passing values between Terraform modules

  • Integrating with other tools and systems

  • Documenting infrastructure attributes

Output Syntax

Basic Output Examples


Output Values Deep Dive

Viewing Outputs

During apply:

Output:

After apply:

Complex Output Examples

Object output:

Conditional output:

Computed from multiple resources:


Sensitive Outputs

Hide sensitive values in Terraform output.

Marking Outputs as Sensitive

Viewing outputs:

Output:

To view sensitive output:

Why Use Sensitive Outputs?

Without sensitive = true:

With sensitive = true:


Real-World Example: Multi-Environment Blog Platform

Let's build a complete multi-environment infrastructure using variables and outputs.

Project Structure

variables.tf

terraform.tfvars (default/shared values)

environments/dev.tfvars

environments/staging.tfvars

environments/production.tfvars

main.tf

outputs.tf

.gitignore

Deploying Different Environments

Development:

Staging:

Production:


Common Mistakes and How to Avoid Them

Mistake #1: Hardcoding Values

Bad:

Good:

Mistake #2: Not Validating Variables

Bad:

Good:

Mistake #3: Exposing Sensitive Values

Bad:

Good:

Mistake #4: Committing Secrets to Git

Bad:

Good:

Mistake #5: Wrong Variable Type

Bad:

Good:


Best Practices for Variables and Outputs

1. Always Provide Descriptions

2. Use Validation for Critical Variables

3. Organize Variables by Purpose

4. Use Sensible Defaults

5. Mark Sensitive Data

7. Environment-Specific Variable Files


What I Learned About Parameterization

1. Variables Enable Reusability

One configuration, infinite environments. That's the power of variables.

Before variables:

  • 3 copies of same code

  • Bug fixes required 3 changes

  • Easy to miss differences

After variables:

  • 1 configuration

  • 3 variable files

  • Consistent infrastructure

2. Validation Catches Mistakes Early

This simple validation has saved me from:

  • Typos ("produciton")

  • Inconsistencies ("PROD" vs "prod")

  • Invalid values ("test", "qa", "uat" when infrastructure doesn't support them)

3. Outputs Are Documentation

Good outputs tell the story of what was created:

4. Sensitive Data Requires Care

  • Mark variables as sensitive = true

  • Mark outputs as sensitive = true

  • Never commit secrets to Git

  • Use environment variables or encrypted files

5. Types Matter

Correct types prevent bugs:

  • number for ports, counts, sizes

  • bool for feature flags

  • list for collections

  • object for structured data


Next Steps

Congratulations! You now understand how to make Terraform configurations flexible and reusable:

βœ… Variable types and declarations βœ… Input variables and .tfvars files βœ… Variable validation βœ… Sensitive variables βœ… Outputs and sensitive outputs βœ… Multi-environment blog platform example

Practice Exercises

Exercise 1: Variable Types

Exercise 2: Multi-Environment Setup

Exercise 3: Validation Rules

Coming Up Next

In Article 4: Mastering HCL - Terraform's Configuration Language, we'll dive deep into:

  • HCL syntax and expressions

  • Built-in functions (50+ functions!)

  • Conditional expressions

  • For expressions and loops

  • Dynamic blocks

  • Local values

  • Complex configuration patterns

Variables are the first step to flexible infrastructure. HCL expressions are how you make those variables work together to create powerful, dynamic configurations.


This Week's Challenge: Build a multi-environment infrastructure with at least 5 variables, validation rules for each, and comprehensive outputs. Deploy to 3 different environments using .tfvars files. Document the differences in a README.

See you in Article 4! 🎯


"Variables turned my copy-paste nightmare into elegant, reusable infrastructure. If you're still copying code between environments, you're doing it wrong." - Me, after deleting 1,500 lines of duplicate code

Last updated