Exercise 2: Variables and Outputs in Terraform
Objective
Learn how to use variables and outputs in Terraform to make configurations more flexible, maintainable, and reusable. This exercise will help you understand variable types, default values, validation, and output formatting.
Prerequisites
- Terraform installed (v1.0.0 or newer)
- Completion of Exercise 1: Your First Terraform Configuration
- For AWS: Access key and secret key with appropriate permissions
- For GCP: Google Cloud account with a project and appropriate credentials
Cloud Provider Selection
This exercise provides implementations for both AWS and GCP. Choose the cloud provider you’re most comfortable with or need to learn for your professional requirements:
Core Concepts Covered
Regardless of the cloud provider chosen, this exercise covers these key Terraform concepts:
- Variable Types
- Basic types (string, number, bool)
- Complex types (list, set, map, object, tuple)
- Optional vs required variables
- Type constraints and validation
- Variable Definition Methods
- Default values in variable blocks
- Value assignment in
.tfvars
files - Command-line assignment with
-var
- Environment variables
- Variable precedence
- Outputs
- Basic output formatting
- Output dependencies
- Sensitive outputs
- Complex output structures
- Local Values
- Defining local values
- Using locals for computed values
- Reducing repetition with locals
Exercise Overview
In both AWS and GCP implementations, you will:
- Create variable definitions with different types
- Implement variable validation
- Create a
.tfvars
file for variable assignment - Use variables throughout your configuration
- Define outputs to extract important information
- Use locals for computed or repeated values
- Apply the configuration using different variable passing methods
Learning Outcomes
After completing this exercise, you should be able to:
- Define and use different variable types
- Implement variable validation
- Understand variable precedence
- Create useful and well-formatted outputs
- Apply local values effectively
- Manage configurations for different environments
Additional Challenges
To further enhance your learning, try these additional challenges after completing the basic exercise:
- Create environment-specific
.tfvars
files (dev, test, prod) - Implement complex validation rules for variables
- Create outputs that combine multiple resource attributes
- Use
for
expressions in locals to transform data - Create a module that accepts variables and returns outputs
Next Steps
After completing this exercise, proceed to Exercise 3: Resource Dependencies, where you’ll learn how to manage dependencies between resources in Terraform.