Terraform
21%
Course progress
2 of 14 topics done
Keep going, you are close!
3 topics in a row
2 of 14 topics done
CoursesdevopsTerraformVariables and Blocks
LessonΒ·3 of 14

Variables and Blocks

N/A14 lessons
1

Variable

πŸ”§ Terraform Variables

TerraformVariablesInput VariablesConfigurationLevelDuration

πŸ“‹ Overview

🎯 Master Terraform Variables for Dynamic Configurations

This guide teaches you how to use variables in Terraform to create reusable, flexible infrastructure configurations that accept input values and produce dynamic outputs.

πŸ” What This Guide Covers

  • πŸ”§ Variable Declaration - Creating and defining variables
  • πŸ“₯ Input Variables - Accepting values from users
  • 🎯 Variable References - Using variables in configurations
  • πŸ“€ Output Variables - Displaying computed values
  • πŸ”„ Variable Interpolation - String interpolation with variables
  • πŸ’Ύ Practical Examples - Real-world variable usage
  • βœ… Best Practices - Variable management recommendations

πŸ”§ What Are Terraform Variables?

DefinitionCore Concept

Variables in Terraform are used to define input values that can be passed to your configuration. They make your infrastructure code reusable and flexible by allowing you to parameterize your configurations instead of hardcoding values.

✨ Key Characteristics

FeatureDescription
ReusabilityDefine once, use multiple times across configurations
FlexibilityAccept different values without changing code
ParameterizationPass values at runtime or via files
Type SafetySupport for various data types (string, number, bool, list, map, object)
Default ValuesOptional default values for variables
ValidationBuilt-in validation rules for variable values

πŸ“₯ Variable Declaration

DeclarationSyntax

Basic Variable Syntax

hcl
variable "variable_name" {
  type        = string
  description = "Description of the variable"
  default     = "default_value"
}

Simple Variable Example

Create a file called variable.tf:

hcl
variable "username" {}

This declares a simple variable named username with no default value or type constraints.

Variable with Type and Description

hcl
variable "instance_count" {
  type        = number
  description = "Number of EC2 instances to create"
  default     = 1
}

🎯 Using Variables in Configuration

UsageImplementation

Referencing Variables

Within a module, variable values are accessed using var.<NAME> syntax:

hcl
# Direct reference
resource "aws_instance" "example" {
  ami           = var.ami_id
  instance_type = var.instance_type
}

# String interpolation
output "greeting" {
  value = "Hello, ${var.username}"
}

Practical Example: Step-by-Step

Step 1: Create variable.tf

hcl
variable "username" {
  type        = string
  description = "The username to greet"
}

Step 2: Create output.tf

hcl
output "printname" {
  value = "Hello, ${var.username}"
}

Step 3: Run Terraform Plan

bash
terraform plan

Expected Output:

text
var.username
Enter a value: DevOpsGuru

Changes to Outputs:
  + printname = "Hello, DevOpsGuru"

Step 4: Apply Configuration

bash
terraform apply

πŸ“€ Output Variables

OutputsResults

Output variables display computed values from your Terraform configuration:

hcl
output "printname" {
  value       = "Hello, ${var.username}"
  description = "Greeting message with username"
}

Output Characteristics

AspectDetails
PurposeExport values from configuration
VisibilityDisplayed after terraform apply
UsageCan be referenced by other modules
StateStored in Terraform state file

πŸ”„ Variable Interpolation

InterpolationString Syntax

String Interpolation Syntax

hcl
# Basic interpolation
"Hello, ${var.username}"

# Multiple variables
"${var.first_name} ${var.last_name}"

# With expressions
"Instance type: ${var.instance_type} with ${var.cpu_count} CPUs"

Complete Example

hcl
variable "environment" {
  type = string
}

variable "app_name" {
  type = string
}

output "resource_name" {
  value = "${var.app_name}-${var.environment}-instance"
}

πŸ’Ύ Practical Examples

ExamplesReal World

Example 1: Simple Greeting

Files Structure:

text
project/
β”œβ”€β”€ variable.tf
└── output.tf

variable.tf:

hcl
variable "username" {
  type        = string
  description = "User's name"
}

output.tf:

hcl
output "greeting" {
  value = "Hello, ${var.username}!"
}

Run:

bash
terraform plan
# Enter value: Alice
# Output: greeting = "Hello, Alice!"

Example 2: Multiple Variables

variable.tf:

hcl
variable "instance_type" {
  type    = string
  default = "t2.micro"
}

variable "instance_count" {
  type    = number
  default = 1
}

variable "environment" {
  type = string
}

output.tf:

hcl
output "configuration" {
  value = "Creating ${var.instance_count} ${var.instance_type} instances in ${var.environment}"
}

βœ… Best Practices

Best PracticesStandards
  • Always provide descriptions for variables to document their purpose
  • Use appropriate types (string, number, bool, list, map) for type safety
  • Set sensible defaults where applicable to reduce required inputs
  • Use meaningful variable names that clearly indicate their purpose
  • Group related variables in the same file or separate files logically
  • Validate variable values using validation blocks when necessary
  • Document variable usage in comments and README files
  • Use variable files (.tfvars) for environment-specific values
  • Avoid hardcoding values - use variables instead for flexibility
  • Keep variables organized in dedicated variable.tf files

πŸ”— Navigation

Navigation

πŸ“ Current Location: Terraform Variables (You are here)

⬅️ Previous Step: Terraform Installation

➑️ Next Step: Pass Variables

πŸ—ΊοΈ Full Path: Introduction β†’ Installation β†’ Variables and Blocks β†’ Provisioner


πŸ“š Additional Resources

ResourcesDocumentation

Terraform Variables

πŸŽ‰ Excellent! Terraform Variables Complete! πŸŽ‰

➑️ Continue to Pass Variables