Variables and Outputs: Making Infrastructure Reusable
Table of Contents
Introduction: The Copy-Paste Nightmare
What Are Variables?
Variables vs Hardcoding
Variable Flow
Variable Types and Declarations
Basic Variable Types
Collection Types
Complex Nested Types
Input Variables Deep Dive
Complete Variable Declaration
Variable Without Default (Required)
Using Variables
Variable Files (.tfvars)
File Structure
Using Variable Files
Variable File Formats
Variable Validation
Basic Validation
Complex Validation Examples
Sensitive Variables
Marking Variables as Sensitive
Sensitive Variable Behavior
Working with Sensitive Values
Providing Sensitive Variables
Variable Precedence
Precedence Order (Lowest to Highest)
Precedence Example
Understanding Outputs
Output Syntax
Basic Output Examples
Output Values Deep Dive
Viewing Outputs
Complex Output Examples
Sensitive Outputs
Marking Outputs as Sensitive
Why Use Sensitive Outputs?
Real-World Example: Multi-Environment Blog Platform
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
Common Mistakes and How to Avoid Them
Mistake #1: Hardcoding Values
Mistake #2: Not Validating Variables
Mistake #3: Exposing Sensitive Values
Mistake #4: Committing Secrets to Git
Mistake #5: Wrong Variable Type
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
6. Use Structured Types for Related Data
7. Environment-Specific Variable Files
What I Learned About Parameterization
1. Variables Enable Reusability
2. Validation Catches Mistakes Early
3. Outputs Are Documentation
4. Sensitive Data Requires Care
5. Types Matter
Next Steps
Practice Exercises
Coming Up Next
PreviousProviders, Resources, and the Magic of State FilesNextMastering HCL: Terraform's Configuration Language
Last updated