Variable
π§ Terraform Variables
π 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?
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
| Feature | Description |
|---|---|
| Reusability | Define once, use multiple times across configurations |
| Flexibility | Accept different values without changing code |
| Parameterization | Pass values at runtime or via files |
| Type Safety | Support for various data types (string, number, bool, list, map, object) |
| Default Values | Optional default values for variables |
| Validation | Built-in validation rules for variable values |
π₯ Variable Declaration
Basic Variable Syntax
variable "variable_name" {
type = string
description = "Description of the variable"
default = "default_value"
}
Simple Variable Example
Create a file called variable.tf:
variable "username" {}
This declares a simple variable named username with no default value or type constraints.
Variable with Type and Description
variable "instance_count" {
type = number
description = "Number of EC2 instances to create"
default = 1
}
π― Using Variables in Configuration
Referencing Variables
Within a module, variable values are accessed using var.<NAME> syntax:
# 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
variable "username" {
type = string
description = "The username to greet"
}
Step 2: Create output.tf
output "printname" {
value = "Hello, ${var.username}"
}
Step 3: Run Terraform Plan
terraform plan
Expected Output:
var.username
Enter a value: DevOpsGuru
Changes to Outputs:
+ printname = "Hello, DevOpsGuru"
Step 4: Apply Configuration
terraform apply
π€ Output Variables
Output variables display computed values from your Terraform configuration:
output "printname" {
value = "Hello, ${var.username}"
description = "Greeting message with username"
}
Output Characteristics
| Aspect | Details |
|---|---|
| Purpose | Export values from configuration |
| Visibility | Displayed after terraform apply |
| Usage | Can be referenced by other modules |
| State | Stored in Terraform state file |
π Variable Interpolation
String Interpolation Syntax
# 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
variable "environment" {
type = string
}
variable "app_name" {
type = string
}
output "resource_name" {
value = "${var.app_name}-${var.environment}-instance"
}
πΎ Practical Examples
Example 1: Simple Greeting
Files Structure:
project/
βββ variable.tf
βββ output.tf
variable.tf:
variable "username" {
type = string
description = "User's name"
}
output.tf:
output "greeting" {
value = "Hello, ${var.username}!"
}
Run:
terraform plan
# Enter value: Alice
# Output: greeting = "Hello, Alice!"
Example 2: Multiple Variables
variable.tf:
variable "instance_type" {
type = string
default = "t2.micro"
}
variable "instance_count" {
type = number
default = 1
}
variable "environment" {
type = string
}
output.tf:
output "configuration" {
value = "Creating ${var.instance_count} ${var.instance_type} instances in ${var.environment}"
}
β Best Practices
- 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
π 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
- π Terraform Variables Documentation: terraform.io/language/values/variables
- π Input Variables Guide: terraform.io/language/values/variables
- π‘ Variable Validation: terraform.io/language/values/variables#validation
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Terraform Variables Complete! π
PassVariable
π€ Passing Variables in Terraform
π Overview
π― Master Multiple Methods to Pass Variables to Terraform
This guide explores various methods to provide variable values to Terraform configurations, including command-line arguments, environment variables, and variable files.
π What This Guide Covers
- π₯οΈ Command-Line Arguments - Using
-varflag - π Variable Files - Using
.tfvarsfiles - π Environment Variables - Using TF_VAR_ prefix
- π Variable Precedence - Understanding priority order
- πΎ Practical Examples - Real-world usage patterns
- β Best Practices - Variable passing recommendations
π₯ Methods to Pass Variables
Variable Input Methods
| Method | Syntax | Use Case |
|---|---|---|
| Command-Line | -var "key=value" | Quick overrides, CI/CD |
| Variable Files | -var-file="file.tfvars" | Environment-specific values |
| Environment Variables | TF_VAR_key=value | Sensitive data, automation |
| Interactive Prompt | Manual input | Development, testing |
| Default Values | In variable block | Fallback values |
π₯οΈ Method 1: Command-Line Arguments
Basic Syntax
terraform plan -var "variable_name=value"
terraform apply -var "variable_name=value"
Single Variable
terraform plan -var "username=DevOpsGuru"
Multiple Variables
terraform plan \
-var "username=DevOpsGuru" \
-var "environment=production" \
-var "instance_count=3"
Example Configuration
variable.tf:
variable "username" {
type = string
}
variable "environment" {
type = string
}
output.tf:
output "info" {
value = "User: ${var.username}, Environment: ${var.environment}"
}
Run:
terraform plan -var "username=Alice" -var "environment=prod"
π Method 2: Variable Files (.tfvars)
Creating Variable Files
terraform.tfvars (automatically loaded):
username = "DevOpsGuru"
environment = "production"
instance_count = 3
custom.tfvars (manually specified):
username = "Alice"
environment = "staging"
instance_count = 1
Using Variable Files
# Automatically loads terraform.tfvars
terraform plan
# Load specific variable file
terraform plan -var-file="custom.tfvars"
# Load multiple variable files
terraform plan \
-var-file="base.tfvars" \
-var-file="prod.tfvars"
Example Project Structure
project/
βββ main.tf
βββ variable.tf
βββ output.tf
βββ terraform.tfvars # Default values
βββ dev.tfvars # Development environment
βββ staging.tfvars # Staging environment
βββ prod.tfvars # Production environment
Environment-Specific Files
dev.tfvars:
environment = "development"
instance_type = "t2.micro"
instance_count = 1
prod.tfvars:
environment = "production"
instance_type = "t2.large"
instance_count = 5
Run:
# Development
terraform plan -var-file="dev.tfvars"
# Production
terraform plan -var-file="prod.tfvars"
π Method 3: Environment Variables
Syntax
Environment variables must be prefixed with TF_VAR_:
export TF_VAR_variable_name=value
terraform plan
Examples
# Single variable
export TF_VAR_username=DevOpsGuru
terraform plan
# Multiple variables
export TF_VAR_username=Alice
export TF_VAR_environment=production
export TF_VAR_instance_count=3
terraform plan
Practical Example
variable.tf:
variable "db_password" {
type = string
sensitive = true
}
variable "api_key" {
type = string
sensitive = true
}
Set environment variables:
export TF_VAR_db_password="secure_password_123"
export TF_VAR_api_key="api_key_xyz"
terraform apply
In Scripts
#!/bin/bash
export TF_VAR_environment="production"
export TF_VAR_region="us-east-1"
export TF_VAR_instance_count=5
terraform plan
terraform apply -auto-approve
π Variable Precedence
Priority Order (Highest to Lowest)
- Command-line
-varflags (highest priority) - Environment variables (
TF_VAR_*) - Variable files (
.tfvars) - Default values in variable blocks
- Interactive prompts (lowest priority)
Example Precedence
# variable.tf
variable "username" {
default = "default_user"
}
# terraform.tfvars
username = "file_user"
# Command execution
export TF_VAR_username="env_user"
terraform plan -var "username=cli_user"
# Result: cli_user (command-line wins)
πΎ Practical Examples
Example 1: Development vs Production
dev.tfvars:
environment = "development"
instance_type = "t2.micro"
instance_count = 1
enable_monitoring = false
prod.tfvars:
environment = "production"
instance_type = "t2.xlarge"
instance_count = 10
enable_monitoring = true
Deploy:
# Development
terraform apply -var-file="dev.tfvars"
# Production
terraform apply -var-file="prod.tfvars"
Example 2: Sensitive Data
variable.tf:
variable "db_password" {
type = string
sensitive = true
}
Secure approach:
export TF_VAR_db_password="$(aws secretsmanager get-secret-value --secret-id db-password --query SecretString --output text)"
terraform apply
Example 3: CI/CD Pipeline
#!/bin/bash
# ci-deploy.sh
ENVIRONMENT=$1
REGION=${2:-us-east-1}
export TF_VAR_environment=$ENVIRONMENT
export TF_VAR_region=$REGION
export TF_VAR_ci_build_id=$CI_BUILD_ID
terraform init
terraform plan -var-file="${ENVIRONMENT}.tfvars"
terraform apply -var-file="${ENVIRONMENT}.tfvars" -auto-approve
β Best Practices
- Use
.tfvarsfiles for environment-specific configurations - Never commit sensitive data to version control
- Use environment variables for secrets and sensitive information
- Document variable requirements in README files
- Use meaningful variable names that clearly indicate their purpose
- Leverage variable precedence strategically for flexibility
- Create separate
.tfvarsfiles for each environment (dev, staging, prod) - Use
.gitignoreto exclude sensitive.tfvarsfiles - Validate variable values before applying changes
- Use
-auto-approvecautiously in automated pipelines
π Navigation
π Current Location: Passing Variables (You are here)
β¬ οΈ Previous Step: Terraform Variables
β‘οΈ Next Step: Multiple Blocks
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Variables Documentation: terraform.io/language/values/variables
- π Variable Files Guide: terraform.io/language/values/variables#variable-files
- π‘ Environment Variables: terraform.io/cli/config/environment-variables
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Passing Variables Complete! π
MultipleBlock
π Multiple Blocks in Terraform
π Overview
π― Master Multiple Blocks and Resource Organization
This guide teaches you how to organize Terraform configurations using multiple blocks, enabling better code structure and maintainability.
π What This Guide Covers
- π Block Types - Understanding different block types
- π¦ Resource Blocks - Creating multiple resources
- π Nested Blocks - Working with nested configurations
- π File Organization - Structuring multiple blocks
- πΎ Practical Examples - Real-world block usage
- β Best Practices - Block organization recommendations
π Understanding Blocks
Block Types in Terraform
| Block Type | Purpose | Example |
|---|---|---|
| resource | Define infrastructure resources | resource "aws_instance" "web" |
| variable | Define input variables | variable "instance_type" |
| output | Define output values | output "instance_ip" |
| provider | Configure providers | provider "aws" |
| terraform | Configure Terraform settings | terraform { required_version } |
| locals | Define local values | locals { common_tags } |
| data | Reference external data | data "aws_ami" "ubuntu" |
Block Syntax
block_type "block_name" "resource_name" {
argument = value
nested_block {
argument = value
}
}
π¦ Multiple Resource Blocks
Creating Multiple Resources
main.tf:
# First resource block
resource "aws_instance" "web_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "web-server"
}
}
# Second resource block
resource "aws_instance" "app_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.small"
tags = {
Name = "app-server"
}
}
# Third resource block
resource "aws_security_group" "web_sg" {
name = "web-security-group"
description = "Security group for web server"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
Organizing Multiple Blocks
Project Structure:
project/
βββ main.tf # Main resources
βββ variable.tf # Input variables
βββ output.tf # Output values
βββ provider.tf # Provider configuration
βββ locals.tf # Local values
π Nested Blocks
Nested Block Example
resource "aws_security_group" "example" {
name = "example-sg"
# Nested ingress block
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
# Another nested ingress block
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
# Nested egress block
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Multiple Nested Blocks
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
# Multiple root_block_device blocks
root_block_device {
volume_type = "gp2"
volume_size = 20
delete_on_termination = true
}
# Multiple ebs_block_device blocks
ebs_block_device {
device_name = "/dev/sdf"
volume_size = 100
volume_type = "gp2"
}
ebs_block_device {
device_name = "/dev/sdg"
volume_size = 50
volume_type = "io1"
iops = 1000
}
}
π File Organization Patterns
Pattern 1: Functional Organization
project/
βββ main.tf # Core resources
βββ networking.tf # Network resources
βββ security.tf # Security groups
βββ compute.tf # EC2 instances
βββ storage.tf # S3, EBS resources
βββ variable.tf # Variables
βββ output.tf # Outputs
βββ provider.tf # Providers
Pattern 2: Environment Organization
project/
βββ environments/
β βββ dev/
β β βββ main.tf
β β βββ variable.tf
β β βββ dev.tfvars
β βββ staging/
β β βββ main.tf
β β βββ variable.tf
β β βββ staging.tfvars
β βββ prod/
β βββ main.tf
β βββ variable.tf
β βββ prod.tfvars
βββ modules/
βββ networking/
βββ compute/
βββ storage/
Pattern 3: Module-Based Organization
project/
βββ main.tf
βββ variable.tf
βββ output.tf
βββ modules/
βββ vpc/
β βββ main.tf
β βββ variable.tf
β βββ output.tf
βββ security_group/
β βββ main.tf
β βββ variable.tf
β βββ output.tf
βββ ec2/
βββ main.tf
βββ variable.tf
βββ output.tf
πΎ Practical Examples
Example 1: Complete Web Application Setup
main.tf:
# VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = {
Name = "main-vpc"
}
}
# Subnet
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "main-subnet"
}
}
# Security Group
resource "aws_security_group" "web" {
name = "web-sg"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# EC2 Instance
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
subnet_id = aws_subnet.main.id
vpc_security_group_ids = [aws_security_group.web.id]
tags = {
Name = "web-server"
}
}
Example 2: Multiple Variables and Outputs
variable.tf:
variable "instance_type" {
type = string
default = "t2.micro"
}
variable "instance_count" {
type = number
default = 1
}
variable "environment" {
type = string
}
output.tf:
output "instance_ids" {
value = aws_instance.web[*].id
}
output "instance_ips" {
value = aws_instance.web[*].private_ip
}
output "security_group_id" {
value = aws_security_group.web.id
}
β Best Practices
- Organize blocks logically by resource type or function
- Use separate files for different concerns (variables, outputs, resources)
- Name resources clearly to indicate their purpose
- Group related blocks together for better readability
- Use consistent indentation and formatting
- Document complex blocks with comments
- Avoid deeply nested blocks - keep nesting to 2-3 levels
- Use locals for repeated values across blocks
- Leverage modules for reusable block collections
- Keep files focused - each file should have a single responsibility
π Navigation
π Current Location: Multiple Blocks (You are here)
β¬ οΈ Previous Step: Passing Variables
β‘οΈ Next Step: Multi Variable
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Blocks Documentation: terraform.io/language/syntax/blocks
- π Resource Syntax: terraform.io/language/resources/syntax
- π‘ Nested Blocks: terraform.io/language/syntax/blocks#nested-blocks
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Multiple Blocks Complete! π
MultiVariable
π’ Multiple Variables in Terraform
π Overview
π― Master Working with Multiple Variables
This guide teaches you how to effectively manage and use multiple variables in Terraform configurations for flexible and reusable infrastructure code.
π What This Guide Covers
- π’ Multiple Variable Declaration - Defining several variables
- π₯ Variable Organization - Structuring multiple variables
- π Variable Dependencies - Using variables together
- πΎ Practical Examples - Real-world multi-variable usage
- β Best Practices - Variable management recommendations
π’ Declaring Multiple Variables
Basic Multiple Variables
variable.tf:
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "instance_count" {
type = number
description = "Number of instances to create"
default = 1
}
variable "environment" {
type = string
description = "Environment name"
}
variable "enable_monitoring" {
type = bool
description = "Enable CloudWatch monitoring"
default = false
}
Variable Types
| Type | Example | Use Case |
|---|---|---|
| string | "t2.micro" | Text values |
| number | 3 | Numeric values |
| bool | true | Boolean flags |
| list | ["a", "b", "c"] | Multiple values |
| map | {key = "value"} | Key-value pairs |
| object | Complex structures | Nested data |
| tuple | ["a", 1, true] | Mixed types |
π₯ Variable Organization
Single File Organization
variable.tf:
# Networking variables
variable "vpc_cidr" {
type = string
description = "VPC CIDR block"
default = "10.0.0.0/16"
}
variable "subnet_cidr" {
type = string
description = "Subnet CIDR block"
default = "10.0.1.0/24"
}
# Compute variables
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "instance_count" {
type = number
description = "Number of instances"
default = 1
}
# General variables
variable "environment" {
type = string
description = "Environment name"
}
variable "project_name" {
type = string
description = "Project name"
}
Multiple File Organization
networking_variables.tf:
variable "vpc_cidr" {
type = string
description = "VPC CIDR block"
default = "10.0.0.0/16"
}
variable "subnet_cidr" {
type = string
description = "Subnet CIDR block"
default = "10.0.1.0/24"
}
compute_variables.tf:
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "instance_count" {
type = number
description = "Number of instances"
default = 1
}
general_variables.tf:
variable "environment" {
type = string
description = "Environment name"
}
variable "project_name" {
type = string
description = "Project name"
}
π Using Multiple Variables Together
Referencing Multiple Variables
main.tf:
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
tags = {
Name = "${var.project_name}-vpc"
Environment = var.environment
}
}
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = var.subnet_cidr
availability_zone = var.availability_zone
tags = {
Name = "${var.project_name}-subnet"
Environment = var.environment
}
}
resource "aws_instance" "web" {
count = var.instance_count
ami = var.ami_id
instance_type = var.instance_type
subnet_id = aws_subnet.main.id
tags = {
Name = "${var.project_name}-instance-${count.index + 1}"
Environment = var.environment
}
}
Variable Dependencies
variable "environment" {
type = string
}
variable "instance_type" {
type = string
# Validation based on environment
validation {
condition = var.environment == "prod" ? var.instance_type != "t2.micro" : true
error_message = "Production environment requires instance type larger than t2.micro."
}
}
πΎ Practical Examples
Example 1: Complete Application Setup
variable.tf:
variable "project_name" {
type = string
description = "Project name"
}
variable "environment" {
type = string
description = "Environment (dev, staging, prod)"
}
variable "region" {
type = string
description = "AWS region"
default = "us-east-1"
}
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "instance_count" {
type = number
description = "Number of instances"
default = 1
}
variable "enable_monitoring" {
type = bool
description = "Enable CloudWatch monitoring"
default = false
}
variable "tags" {
type = map(string)
description = "Common tags for all resources"
default = {
Terraform = "true"
}
}
dev.tfvars:
project_name = "myapp"
environment = "development"
region = "us-east-1"
instance_type = "t2.micro"
instance_count = 1
enable_monitoring = false
prod.tfvars:
project_name = "myapp"
environment = "production"
region = "us-east-1"
instance_type = "t2.large"
instance_count = 5
enable_monitoring = true
Example 2: Using Multiple Variables in Outputs
output.tf:
output "instance_ids" {
value = aws_instance.web[*].id
description = "IDs of created instances"
}
output "instance_ips" {
value = aws_instance.web[*].private_ip
description = "Private IPs of instances"
}
output "environment_info" {
value = {
project = var.project_name
environment = var.environment
region = var.region
instance_count = var.instance_count
}
description = "Environment configuration summary"
}
Example 3: Complex Variable Types
variable.tf:
variable "instance_config" {
type = object({
instance_type = string
instance_count = number
root_volume_size = number
enable_monitoring = bool
})
description = "EC2 instance configuration"
default = {
instance_type = "t2.micro"
instance_count = 1
root_volume_size = 20
enable_monitoring = false
}
}
variable "security_group_rules" {
type = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
description = "Security group ingress rules"
default = [
{
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}
β Best Practices
- Group related variables together logically
- Use descriptive names that clearly indicate purpose
- Provide descriptions for all variables
- Set sensible defaults where applicable
- Use appropriate types for type safety
- Organize variables in separate files by concern
- Document variable relationships in comments
- Use validation blocks for complex requirements
- Keep variable files focused on specific domains
- Use consistent naming conventions across all variables
π Navigation
π Current Location: Multiple Variables (You are here)
β¬ οΈ Previous Step: Multiple Blocks
β‘οΈ Next Step: Variable Types
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Variables Documentation: terraform.io/language/values/variables
- π Variable Types: terraform.io/language/values/variables#type-constraints
- π‘ Variable Validation: terraform.io/language/values/variables#validation
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Multiple Variables Complete! π
VariableType
π Variable Types in Terraform
π Overview
π― Master Terraform Variable Types for Type-Safe Configurations
This guide explores all variable types available in Terraform, enabling you to create robust and type-safe infrastructure configurations.
π What This Guide Covers
- π Primitive Types - String, number, bool
- π¦ Collection Types - List, map, set
- π Complex Types - Object, tuple
- π― Type Constraints - Enforcing types
- πΎ Practical Examples - Real-world type usage
- β Best Practices - Type management recommendations
π Terraform Variable Types
Type Categories
| Category | Types | Purpose |
|---|---|---|
| Primitive | string, number, bool | Basic data types |
| Collection | list, map, set | Multiple values |
| Complex | object, tuple | Structured data |
| Special | any | Any type (use sparingly) |
π€ String Type
String Variable Declaration
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "environment" {
type = string
description = "Environment name"
}
variable "region" {
type = string
description = "AWS region"
default = "us-east-1"
}
String Usage
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "web-server"
Environment = var.environment
}
}
String Interpolation
output "instance_info" {
value = "Instance type: ${var.instance_type} in ${var.region}"
}
π’ Number Type
Number Variable Declaration
variable "instance_count" {
type = number
description = "Number of instances"
default = 1
}
variable "volume_size" {
type = number
description = "EBS volume size in GB"
default = 20
}
variable "port" {
type = number
description = "Port number"
default = 80
}
Number Usage
resource "aws_instance" "web" {
count = var.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "instance-${count.index + 1}"
}
}
resource "aws_ebs_volume" "data" {
availability_zone = "us-east-1a"
size = var.volume_size
}
β Boolean Type
Boolean Variable Declaration
variable "enable_monitoring" {
type = bool
description = "Enable CloudWatch monitoring"
default = false
}
variable "enable_encryption" {
type = bool
description = "Enable encryption"
default = true
}
variable "publicly_accessible" {
type = bool
description = "Make resource publicly accessible"
default = false
}
Boolean Usage
resource "aws_db_instance" "main" {
allocated_storage = 20
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t2.micro"
publicly_accessible = var.publicly_accessible
storage_encrypted = var.enable_encryption
enable_cloudwatch_logs_exports = var.enable_monitoring ? ["error", "general"] : []
}
π List Type
List Variable Declaration
# List of strings
variable "availability_zones" {
type = list(string)
description = "List of availability zones"
default = ["us-east-1a", "us-east-1b"]
}
# List of numbers
variable "ports" {
type = list(number)
description = "List of ports"
default = [80, 443, 8080]
}
# List without type constraint
variable "tags_list" {
type = list(any)
description = "List of tags"
default = ["web", "production", 2024]
}
List Usage
resource "aws_security_group" "web" {
name = "web-sg"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
resource "aws_subnet" "main" {
for_each = toset(var.availability_zones)
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${index(var.availability_zones, each.value)}.0/24"
availability_zone = each.value
}
πΊοΈ Map Type
Map Variable Declaration
# Map of strings
variable "tags" {
type = map(string)
description = "Tags for resources"
default = {
Environment = "production"
Team = "devops"
Project = "myapp"
}
}
# Map of numbers
variable "instance_specs" {
type = map(number)
description = "Instance specifications"
default = {
cpu = 2
memory = 4
disk = 100
}
}
Map Usage
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = var.tags
}
resource "aws_s3_bucket_tag" "example" {
bucket = aws_s3_bucket.example.id
for_each = var.tags
key = each.key
value = each.value
}
π Object Type
Object Variable Declaration
variable "instance_config" {
type = object({
instance_type = string
instance_count = number
root_volume_size = number
enable_monitoring = bool
})
description = "EC2 instance configuration"
default = {
instance_type = "t2.micro"
instance_count = 1
root_volume_size = 20
enable_monitoring = false
}
}
variable "database_config" {
type = object({
engine = string
engine_version = string
instance_class = string
allocated_storage = number
backup_retention_days = number
})
description = "RDS database configuration"
}
Object Usage
resource "aws_instance" "web" {
count = var.instance_config.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_config.instance_type
root_block_device {
volume_size = var.instance_config.root_volume_size
}
}
resource "aws_db_instance" "main" {
engine = var.database_config.engine
engine_version = var.database_config.engine_version
instance_class = var.database_config.instance_class
allocated_storage = var.database_config.allocated_storage
backup_retention_days = var.database_config.backup_retention_days
}
π― Tuple Type
Tuple Variable Declaration
variable "mixed_data" {
type = tuple([string, number, bool])
description = "Tuple with mixed types"
default = ["example", 42, true]
}
variable "config_tuple" {
type = tuple([
string, # name
number, # port
bool, # enabled
list(string) # tags
])
description = "Configuration tuple"
default = ["myapp", 8080, true, ["web", "api"]]
}
Tuple Usage
output "tuple_values" {
value = {
name = var.mixed_data[0]
count = var.mixed_data[1]
enabled = var.mixed_data[2]
}
}
πΎ Practical Examples
Example 1: Complete Type Usage
variable.tf:
variable "project_name" {
type = string
}
variable "environment" {
type = string
}
variable "instance_count" {
type = number
default = 1
}
variable "enable_monitoring" {
type = bool
default = false
}
variable "availability_zones" {
type = list(string)
default = ["us-east-1a", "us-east-1b"]
}
variable "tags" {
type = map(string)
default = {
Terraform = "true"
}
}
variable "instance_config" {
type = object({
instance_type = string
root_volume_size = number
})
default = {
instance_type = "t2.micro"
root_volume_size = 20
}
}
Example 2: Complex Configuration
variable.tf:
variable "security_groups" {
type = list(object({
name = string
description = string
ingress_rules = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
}))
}
β Best Practices
- Always specify types for variables to ensure type safety
- Use primitive types for simple values (string, number, bool)
- Use collection types for multiple values (list, map)
- Use object types for structured, complex data
- Provide meaningful defaults where applicable
- Document type constraints in descriptions
- Validate complex types using validation blocks
- Keep object structures simple - avoid deep nesting
- Use consistent naming for object properties
- Leverage type safety to catch configuration errors early
π Navigation
π Current Location: Variable Types (You are here)
β¬ οΈ Previous Step: Multiple Variables
β‘οΈ Next Step: Tfvars Files
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Type Constraints: terraform.io/language/values/variables#type-constraints
- π Type System: terraform.io/language/types
- π‘ Complex Types: terraform.io/language/types#complex-types
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Variable Types Complete! π
Tfvars
π Terraform .tfvars Files
π Overview
π― Master Terraform .tfvars Files for Configuration Management
This guide teaches you how to use
.tfvarsfiles to manage variable values, enabling environment-specific configurations and better code organization.
π What This Guide Covers
- π Tfvars File Basics - Understanding
.tfvarsfiles - π§ Creating Tfvars Files - Syntax and structure
- π Environment-Specific Files - Dev, staging, production
- π Loading Tfvars Files - Using
-var-fileflag - πΎ Practical Examples - Real-world usage patterns
- β Best Practices - Tfvars management recommendations
π What Are Tfvars Files?
Tfvars File Characteristics
| Aspect | Details |
|---|---|
| Extension | .tfvars or .tfvars.json |
| Purpose | Store variable values for Terraform configurations |
| Format | HCL or JSON syntax |
| Automatic Loading | terraform.tfvars loaded automatically |
| Manual Loading | Other files loaded with -var-file flag |
| Precedence | Lower priority than CLI -var flags |
File Types
terraform.tfvars # Automatically loaded
terraform.tfvars.json # JSON format, automatically loaded
custom.tfvars # Manually specified
dev.tfvars # Development environment
staging.tfvars # Staging environment
prod.tfvars # Production environment
π§ Creating Tfvars Files
HCL Format
terraform.tfvars:
# String variables
instance_type = "t2.micro"
environment = "production"
region = "us-east-1"
# Number variables
instance_count = 3
port = 8080
# Boolean variables
enable_monitoring = true
publicly_accessible = false
# List variables
availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
ports = [80, 443, 8080]
# Map variables
tags = {
Environment = "production"
Team = "devops"
Project = "myapp"
}
# Object variables
instance_config = {
instance_type = "t2.micro"
instance_count = 1
root_volume_size = 20
enable_monitoring = false
}
JSON Format
terraform.tfvars.json:
{
"instance_type": "t2.micro",
"environment": "production",
"region": "us-east-1",
"instance_count": 3,
"enable_monitoring": true,
"availability_zones": ["us-east-1a", "us-east-1b"],
"tags": {
"Environment": "production",
"Team": "devops"
}
}
π Environment-Specific Tfvars Files
Development Environment
dev.tfvars:
environment = "development"
instance_type = "t2.micro"
instance_count = 1
enable_monitoring = false
enable_encryption = false
backup_retention = 1
tags = {
Environment = "development"
Team = "devops"
CostCenter = "engineering"
}
Staging Environment
staging.tfvars:
environment = "staging"
instance_type = "t2.small"
instance_count = 2
enable_monitoring = true
enable_encryption = true
backup_retention = 7
tags = {
Environment = "staging"
Team = "devops"
CostCenter = "engineering"
}
Production Environment
prod.tfvars:
environment = "production"
instance_type = "t2.large"
instance_count = 5
enable_monitoring = true
enable_encryption = true
backup_retention = 30
tags = {
Environment = "production"
Team = "devops"
CostCenter = "operations"
}
π Loading Tfvars Files
Automatic Loading
# terraform.tfvars is automatically loaded
terraform plan
terraform apply
Manual Loading
# Load specific tfvars file
terraform plan -var-file="dev.tfvars"
terraform apply -var-file="dev.tfvars"
# Load multiple tfvars files
terraform plan \
-var-file="base.tfvars" \
-var-file="dev.tfvars"
# Load with custom filename
terraform plan -var-file="custom-config.tfvars"
Loading Order
# Multiple files are loaded in order (later values override earlier)
terraform plan \
-var-file="defaults.tfvars" \
-var-file="dev.tfvars" \
-var "instance_count=10"
πΎ Practical Examples
Example 1: Project Structure
project/
βββ main.tf
βββ variable.tf
βββ output.tf
βββ terraform.tfvars # Default values
βββ dev.tfvars # Development
βββ staging.tfvars # Staging
βββ prod.tfvars # Production
βββ .gitignore
Example 2: Complete Tfvars Setup
variable.tf:
variable "project_name" {
type = string
}
variable "environment" {
type = string
}
variable "instance_type" {
type = string
default = "t2.micro"
}
variable "instance_count" {
type = number
default = 1
}
variable "enable_monitoring" {
type = bool
default = false
}
variable "tags" {
type = map(string)
}
dev.tfvars:
project_name = "myapp"
environment = "development"
instance_type = "t2.micro"
instance_count = 1
enable_monitoring = false
tags = {
Environment = "development"
Team = "devops"
ManagedBy = "terraform"
}
prod.tfvars:
project_name = "myapp"
environment = "production"
instance_type = "t2.large"
instance_count = 5
enable_monitoring = true
tags = {
Environment = "production"
Team = "devops"
ManagedBy = "terraform"
CostCenter = "operations"
}
Example 3: Deployment Script
deploy.sh:
#!/bin/bash
ENVIRONMENT=$1
if [ -z "$ENVIRONMENT" ]; then
echo "Usage: ./deploy.sh [dev|staging|prod]"
exit 1
fi
TFVARS_FILE="${ENVIRONMENT}.tfvars"
if [ ! -f "$TFVARS_FILE" ]; then
echo "Error: $TFVARS_FILE not found"
exit 1
fi
echo "Deploying to $ENVIRONMENT environment..."
terraform init
terraform plan -var-file="$TFVARS_FILE" -out=tfplan
terraform apply tfplan
echo "Deployment complete!"
Usage:
chmod +x deploy.sh
./deploy.sh dev
./deploy.sh prod
π Security Best Practices
Protecting Sensitive Data
.gitignore:
# Exclude tfvars files with sensitive data
*.tfvars
*.tfvars.json
!example.tfvars
# Exclude state files
*.tfstate
*.tfstate.*
# Exclude plan files
*.tfplan
Using Sensitive Variables
variable.tf:
variable "db_password" {
type = string
sensitive = true
description = "Database password"
}
variable "api_key" {
type = string
sensitive = true
description = "API key"
}
Environment Variables for Secrets
# Use environment variables for sensitive data
export TF_VAR_db_password="$(aws secretsmanager get-secret-value --secret-id db-password --query SecretString --output text)"
export TF_VAR_api_key="$(aws secretsmanager get-secret-value --secret-id api-key --query SecretString --output text)"
terraform apply -var-file="prod.tfvars"
β Best Practices
- Create separate
.tfvarsfiles for each environment - Never commit sensitive data to version control
- Use
.gitignoreto exclude sensitive.tfvarsfiles - Document variable requirements in README files
- Use meaningful filenames that indicate their purpose
- Keep
.tfvarsfiles organized in a dedicated directory - Use environment variables for secrets and sensitive information
- Validate
.tfvarsfiles before applying changes - Use version control for non-sensitive
.tfvarsfiles - Document the purpose of each
.tfvarsfile
π Navigation
π Current Location: Tfvars Files (You are here)
β¬ οΈ Previous Step: Variable Types
β‘οΈ Next Step: Environment Variables
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Variable Files: terraform.io/language/values/variables#variable-files
- π Tfvars File Format: terraform.io/language/values/variables#variable-files
- π‘ Sensitive Variables: terraform.io/language/values/variables#sensitive
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Tfvars Files Complete! π
EnvVariable
π Environment Variables in Terraform
π Overview
π― Master Environment Variables for Terraform Configuration
This guide teaches you how to use environment variables to pass values to Terraform, enabling secure and flexible infrastructure management.
π What This Guide Covers
- π Environment Variable Basics - Understanding TF_VAR_ prefix
- π§ Setting Variables - Exporting environment variables
- π Sensitive Data - Handling secrets securely
- π» Shell Integration - Using variables in scripts
- πΎ Practical Examples - Real-world usage patterns
- β Best Practices - Environment variable recommendations
π Environment Variable Basics
TF_VAR_ Prefix Convention
Terraform automatically recognizes environment variables prefixed with TF_VAR_:
# Environment variable format
TF_VAR_variable_name=value
# Terraform reads this as
var.variable_name = value
Variable Mapping
| Environment Variable | Terraform Variable |
|---|---|
TF_VAR_instance_type | var.instance_type |
TF_VAR_environment | var.environment |
TF_VAR_db_password | var.db_password |
TF_VAR_instance_count | var.instance_count |
π§ Setting Environment Variables
Bash/Linux/macOS
# Export single variable
export TF_VAR_instance_type="t2.micro"
# Export multiple variables
export TF_VAR_environment="production"
export TF_VAR_instance_count=3
export TF_VAR_enable_monitoring=true
# Verify variables are set
echo $TF_VAR_instance_type
env | grep TF_VAR
PowerShell (Windows)
# Set single variable
$env:TF_VAR_instance_type = "t2.micro"
# Set multiple variables
$env:TF_VAR_environment = "production"
$env:TF_VAR_instance_count = "3"
$env:TF_VAR_enable_monitoring = "true"
# Verify variables are set
$env:TF_VAR_instance_type
Get-ChildItem env: | Where-Object {$_.Name -like "TF_VAR_*"}
Command-Line Inline
# Set variable for single command
TF_VAR_instance_type="t2.micro" terraform plan
# Multiple variables
TF_VAR_environment="prod" TF_VAR_instance_count=5 terraform apply
π₯ Using Environment Variables
Variable Declaration
variable.tf:
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "environment" {
type = string
description = "Environment name"
}
variable "instance_count" {
type = number
description = "Number of instances"
default = 1
}
variable "enable_monitoring" {
type = bool
description = "Enable monitoring"
default = false
}
Using in Configuration
main.tf:
resource "aws_instance" "web" {
count = var.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "instance-${count.index + 1}"
Environment = var.environment
}
}
Terraform Execution
# Set environment variables
export TF_VAR_instance_type="t2.small"
export TF_VAR_environment="production"
export TF_VAR_instance_count=3
# Run Terraform
terraform plan
terraform apply
π Handling Sensitive Data
Sensitive Variable Declaration
variable.tf:
variable "db_password" {
type = string
sensitive = true
description = "Database password"
}
variable "api_key" {
type = string
sensitive = true
description = "API key"
}
variable "aws_secret_key" {
type = string
sensitive = true
description = "AWS secret access key"
}
Setting Sensitive Variables
# Set sensitive variables
export TF_VAR_db_password="secure_password_123"
export TF_VAR_api_key="api_key_xyz"
export TF_VAR_aws_secret_key="secret_key_abc"
# Run Terraform (sensitive values won't be displayed)
terraform apply
Retrieving from Secrets Manager
# AWS Secrets Manager
export TF_VAR_db_password=$(aws secretsmanager get-secret-value \
--secret-id db-password \
--query SecretString \
--output text)
# HashiCorp Vault
export TF_VAR_api_key=$(vault kv get -field=api_key secret/myapp)
# Run Terraform
terraform apply
π» Shell Integration
Bash Script Example
deploy.sh:
#!/bin/bash
# Set environment variables
export TF_VAR_environment="production"
export TF_VAR_region="us-east-1"
export TF_VAR_instance_count=5
export TF_VAR_instance_type="t2.large"
# Retrieve sensitive data
export TF_VAR_db_password=$(aws secretsmanager get-secret-value \
--secret-id db-password \
--query SecretString \
--output text)
# Run Terraform
terraform init
terraform plan -out=tfplan
terraform apply tfplan
echo "Deployment complete!"
PowerShell Script Example
deploy.ps1:
# Set environment variables
$env:TF_VAR_environment = "production"
$env:TF_VAR_region = "us-east-1"
$env:TF_VAR_instance_count = "5"
$env:TF_VAR_instance_type = "t2.large"
# Retrieve sensitive data
$secret = aws secretsmanager get-secret-value `
--secret-id db-password `
--query SecretString `
--output text
$env:TF_VAR_db_password = $secret
# Run Terraform
terraform init
terraform plan -out=tfplan
terraform apply tfplan
Write-Host "Deployment complete!"
Environment File
.env:
export TF_VAR_environment="development"
export TF_VAR_region="us-east-1"
export TF_VAR_instance_count=1
export TF_VAR_instance_type="t2.micro"
export TF_VAR_enable_monitoring=false
Usage:
source .env
terraform plan
πΎ Practical Examples
Example 1: Development Environment
#!/bin/bash
# Development environment setup
export TF_VAR_environment="development"
export TF_VAR_region="us-east-1"
export TF_VAR_instance_type="t2.micro"
export TF_VAR_instance_count=1
export TF_VAR_enable_monitoring=false
export TF_VAR_backup_retention=1
terraform plan
terraform apply
Example 2: Production Environment
#!/bin/bash
# Production environment setup
export TF_VAR_environment="production"
export TF_VAR_region="us-east-1"
export TF_VAR_instance_type="t2.large"
export TF_VAR_instance_count=5
export TF_VAR_enable_monitoring=true
export TF_VAR_backup_retention=30
# Retrieve secrets
export TF_VAR_db_password=$(aws secretsmanager get-secret-value \
--secret-id prod/db-password \
--query SecretString \
--output text)
export TF_VAR_api_key=$(aws secretsmanager get-secret-value \
--secret-id prod/api-key \
--query SecretString \
--output text)
terraform plan
terraform apply
Example 3: CI/CD Pipeline
#!/bin/bash
# CI/CD environment setup
export TF_VAR_environment=$CI_ENVIRONMENT
export TF_VAR_region=$AWS_REGION
export TF_VAR_instance_count=$INSTANCE_COUNT
export TF_VAR_build_id=$CI_BUILD_ID
export TF_VAR_commit_sha=$CI_COMMIT_SHA
# Retrieve secrets from CI/CD system
export TF_VAR_db_password=$DB_PASSWORD
export TF_VAR_api_key=$API_KEY
terraform init
terraform plan -var-file="${CI_ENVIRONMENT}.tfvars"
terraform apply -var-file="${CI_ENVIRONMENT}.tfvars" -auto-approve
π Variable Precedence
Priority Order (Highest to Lowest)
- Command-line
-varflags (highest priority) - Environment variables (
TF_VAR_*) - Variable files (
.tfvars) - Default values in variable blocks
- Interactive prompts (lowest priority)
Example
# variable.tf
variable "instance_type" {
default = "t2.micro"
}
# terraform.tfvars
instance_type = "t2.small"
# Environment variable
export TF_VAR_instance_type="t2.medium"
# Command execution
terraform plan -var "instance_type=t2.large"
# Result: t2.large (command-line wins)
β Best Practices
- Use environment variables for sensitive data (passwords, keys)
- Never hardcode secrets in configuration files
- Use
.gitignoreto exclude.envfiles from version control - Document required environment variables in README files
- Use meaningful variable names that clearly indicate their purpose
- Validate environment variables before running Terraform
- Use
sensitive = truefor sensitive variables - Retrieve secrets from secure vaults (AWS Secrets Manager, HashiCorp Vault)
- Use scripts to manage environment variable setup
- Test environment variable configuration before production deployment
π Navigation
π Current Location: Environment Variables (You are here)
β¬ οΈ Previous Step: Tfvars Files
β‘οΈ Next Step: Blocks
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Environment Variables: terraform.io/cli/config/environment-variables
- π Variable Files: terraform.io/language/values/variables#variable-files
- π‘ Sensitive Variables: terraform.io/language/values/variables#sensitive
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Environment Variables Complete! π
Block
π§© Terraform Blocks
π Overview
π― Master Terraform Blocks for Advanced Configuration
This guide explores all block types in Terraform, enabling you to create sophisticated and well-organized infrastructure configurations.
π What This Guide Covers
- π§© Block Types - Understanding all block types
- π¦ Resource Blocks - Creating infrastructure resources
- π§ Data Blocks - Referencing external data
- π Local Blocks - Defining local values
- π Provider Blocks - Configuring providers
- πΎ Practical Examples - Real-world block usage
- β Best Practices - Block organization recommendations
π§© Terraform Block Types
Block Type Overview
| Block Type | Purpose | Syntax |
|---|---|---|
| resource | Define infrastructure resources | resource "type" "name" |
| variable | Define input variables | variable "name" |
| output | Define output values | output "name" |
| provider | Configure providers | provider "name" |
| terraform | Configure Terraform settings | terraform { } |
| locals | Define local values | locals { } |
| data | Reference external data | data "type" "name" |
| module | Use reusable modules | module "name" |
π¦ Resource Blocks
Resource Block Syntax
resource "resource_type" "resource_name" {
argument = value
nested_block {
argument = value
}
}
Resource Block Examples
# EC2 Instance
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "web-server"
}
}
# S3 Bucket
resource "aws_s3_bucket" "data" {
bucket = "my-data-bucket"
tags = {
Name = "data-bucket"
}
}
# Security Group
resource "aws_security_group" "web" {
name = "web-sg"
description = "Security group for web server"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Referencing Resources
# Reference another resource
resource "aws_instance" "app" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.small"
vpc_security_group_ids = [aws_security_group.web.id]
depends_on = [aws_security_group.web]
}
π§ Data Blocks
Data Block Syntax
data "data_source_type" "data_source_name" {
argument = value
}
Data Block Examples
# Get latest Ubuntu AMI
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}
# Get availability zones
data "aws_availability_zones" "available" {
state = "available"
}
# Get VPC information
data "aws_vpc" "default" {
default = true
}
# Get subnets
data "aws_subnets" "default" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}
Using Data Sources
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
availability_zone = data.aws_availability_zones.available.names[0]
tags = {
Name = "web-server"
}
}
π Local Blocks
Local Block Syntax
locals {
local_name = value
another_local = expression
}
Local Block Examples
locals {
# Simple values
environment = "production"
region = "us-east-1"
# Computed values
common_tags = {
Environment = local.environment
ManagedBy = "terraform"
CreatedAt = timestamp()
}
# Complex expressions
instance_count = var.environment == "prod" ? 5 : 1
instance_type = var.environment == "prod" ? "t2.large" : "t2.micro"
}
Using Locals
resource "aws_instance" "web" {
count = local.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = local.instance_type
tags = merge(
local.common_tags,
{
Name = "instance-${count.index + 1}"
}
)
}
π Provider Blocks
Provider Block Syntax
provider "provider_name" {
argument = value
}
Provider Block Examples
# AWS Provider
provider "aws" {
region = "us-east-1"
default_tags {
tags = {
Environment = "production"
ManagedBy = "terraform"
}
}
}
# Multiple AWS Providers (different regions)
provider "aws" {
alias = "us-west"
region = "us-west-2"
}
provider "aws" {
alias = "eu-west"
region = "eu-west-1"
}
# Google Cloud Provider
provider "google" {
project = "my-project"
region = "us-central1"
}
# Azure Provider
provider "azurerm" {
features {}
}
Using Provider Aliases
resource "aws_instance" "us_east" {
provider = aws
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
resource "aws_instance" "us_west" {
provider = aws.us-west
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
βοΈ Terraform Blocks
Terraform Block Syntax
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
Terraform Block Examples
# Specify required Terraform version
terraform {
required_version = ">= 1.0"
}
# Specify required providers
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
google = {
source = "hashicorp/google"
version = "~> 5.0"
}
}
}
# Configure backend
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "terraform.tfstate"
region = "us-east-1"
}
}
π Module Blocks
Module Block Syntax
module "module_name" {
source = "path/to/module"
argument = value
}
Module Block Examples
# Local module
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
environment = var.environment
}
# Registry module
module "security_group" {
source = "terraform-aws-modules/security-group/aws"
version = "~> 4.0"
name = "web-sg"
description = "Security group for web server"
vpc_id = module.vpc.vpc_id
ingress_rules = ["http-80-tcp", "https-443-tcp"]
egress_rules = ["all-all"]
}
# GitHub module
module "database" {
source = "git::https://github.com/example/terraform-modules.git//rds"
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t2.micro"
}
πΎ Practical Examples
Example 1: Complete Configuration
main.tf:
# Data source
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}
# Local values
locals {
common_tags = {
Environment = var.environment
ManagedBy = "terraform"
}
}
# Resource
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
tags = merge(
local.common_tags,
{
Name = "web-server"
}
)
}
Example 2: Multi-Provider Setup
main.tf:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
google = {
source = "hashicorp/google"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
provider "google" {
project = "my-project"
region = "us-central1"
}
# AWS resources
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
# Google resources
resource "google_compute_instance" "app" {
name = "app-server"
machine_type = "e2-medium"
zone = "us-central1-a"
}
β Best Practices
- Organize blocks logically by type and purpose
- Use data sources to reference existing infrastructure
- Use locals for repeated values and computed expressions
- Specify provider versions in terraform blocks
- Use modules for reusable infrastructure patterns
- Document block purposes with comments
- Keep blocks focused on single responsibilities
- Use meaningful names for all blocks
- Validate block syntax before applying
- Follow naming conventions consistently
π Navigation
π Current Location: Blocks (You are here)
β¬ οΈ Previous Step: Environment Variables
β‘οΈ Next Step: Dynamic Blocks
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Terraform Blocks Documentation: terraform.io/language/syntax/blocks
- π Resource Syntax: terraform.io/language/resources/syntax
- π‘ Data Sources: terraform.io/language/data-sources
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Terraform Blocks Complete! π
DynamicBlock
π Dynamic Blocks in Terraform
π Overview
π― Master Dynamic Blocks for Flexible Terraform Configurations
This guide teaches you how to use dynamic blocks to generate nested blocks programmatically, enabling more flexible and DRY infrastructure code.
π What This Guide Covers
- π Dynamic Block Basics - Understanding dynamic blocks
- π Iteration - Looping through collections
- π― Use Cases - When to use dynamic blocks
- πΎ Practical Examples - Real-world dynamic block usage
- β οΈ Common Pitfalls - Avoiding mistakes
- β Best Practices - Dynamic block recommendations
π Dynamic Block Basics
What Are Dynamic Blocks?
Dynamic blocks allow you to generate nested blocks dynamically based on collections (lists, maps, sets). They reduce code repetition and make configurations more maintainable.
Dynamic Block Syntax
dynamic "block_name" {
for_each = collection
content {
argument = block_name.value.property
}
}
Key Components
| Component | Purpose |
|---|---|
| dynamic | Keyword to declare dynamic block |
| block_name | Name of the nested block to generate |
| for_each | Collection to iterate over |
| content | Block content to generate |
| block_name.value | Current item in iteration |
| block_name.key | Current key (for maps) |
π Iteration Patterns
Iterating Over Lists
variable "ports" {
type = list(number)
default = [80, 443, 8080]
}
resource "aws_security_group" "web" {
name = "web-sg"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
Iterating Over Maps
variable "security_rules" {
type = map(object({
from_port = number
to_port = number
protocol = string
}))
default = {
http = {
from_port = 80
to_port = 80
protocol = "tcp"
}
https = {
from_port = 443
to_port = 443
protocol = "tcp"
}
}
}
resource "aws_security_group" "web" {
name = "web-sg"
dynamic "ingress" {
for_each = var.security_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ["0.0.0.0/0"]
}
}
}
Iterating Over Objects
variable "ingress_rules" {
type = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
default = [
{
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}
resource "aws_security_group" "web" {
name = "web-sg"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
}
π― Common Use Cases
Use Case 1: Security Group Rules
variable "ingress_rules" {
type = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
}
resource "aws_security_group" "main" {
name = "main-sg"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
}
Use Case 2: EBS Block Devices
variable "ebs_volumes" {
type = list(object({
device_name = string
volume_size = number
volume_type = string
}))
default = []
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
dynamic "ebs_block_device" {
for_each = var.ebs_volumes
content {
device_name = ebs_block_device.value.device_name
volume_size = ebs_block_device.value.volume_size
volume_type = ebs_block_device.value.volume_type
}
}
}
Use Case 3: Environment Variables
variable "environment_variables" {
type = map(string)
default = {
NODE_ENV = "production"
LOG_LEVEL = "info"
}
}
resource "aws_lambda_function" "app" {
filename = "lambda.zip"
function_name = "my-function"
role = aws_iam_role.lambda.arn
handler = "index.handler"
dynamic "environment" {
for_each = length(var.environment_variables) > 0 ? [1] : []
content {
variables = var.environment_variables
}
}
}
Use Case 4: Tags
variable "tags" {
type = map(string)
default = {
Environment = "production"
Team = "devops"
}
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
dynamic "tag" {
for_each = var.tags
content {
key = tag.key
value = tag.value
}
}
}
πΎ Practical Examples
Example 1: Complete Security Group
variable.tf:
variable "ingress_rules" {
type = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
default = [
{
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
}
]
}
main.tf:
resource "aws_security_group" "web" {
name = "web-sg"
description = "Security group for web server"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Example 2: EC2 with Multiple Volumes
variable.tf:
variable "ebs_volumes" {
type = list(object({
device_name = string
volume_size = number
volume_type = string
}))
default = [
{
device_name = "/dev/sdf"
volume_size = 100
volume_type = "gp2"
},
{
device_name = "/dev/sdg"
volume_size = 50
volume_type = "io1"
}
]
}
main.tf:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
dynamic "ebs_block_device" {
for_each = var.ebs_volumes
content {
device_name = ebs_block_device.value.device_name
volume_size = ebs_block_device.value.volume_size
volume_type = ebs_block_device.value.volume_type
}
}
tags = {
Name = "web-server"
}
}
Example 3: Conditional Dynamic Blocks
variable "enable_monitoring" {
type = bool
default = false
}
variable "monitoring_config" {
type = object({
enabled = bool
level = string
})
default = {
enabled = false
level = "basic"
}
}
resource "aws_db_instance" "main" {
allocated_storage = 20
engine = "mysql"
instance_class = "db.t2.micro"
# Only create monitoring block if enabled
dynamic "monitoring" {
for_each = var.monitoring_config.enabled ? [1] : []
content {
enabled = true
monitoring_role_arn = aws_iam_role.rds_monitoring.arn
monitoring_interval = 60
}
}
}
β οΈ Common Pitfalls
Pitfall 1: Over-Using Dynamic Blocks
# β Bad: Too complex, hard to read
dynamic "ingress" {
for_each = flatten([
for rule in var.rules : [
for port in rule.ports : {
port = port
protocol = rule.protocol
}
]
])
content {
from_port = ingress.value.port
to_port = ingress.value.port
protocol = ingress.value.protocol
}
}
# β
Good: Simpler, more readable
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
Pitfall 2: Incorrect Variable Reference
# β Bad: Wrong reference
dynamic "ingress" {
for_each = var.ports
content {
from_port = var.ports[0] # Wrong!
}
}
# β
Good: Correct reference
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value # Correct!
}
}
Pitfall 3: Empty Collections
# β Bad: May cause errors with empty list
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
}
}
# β
Good: Handle empty collections
dynamic "ingress" {
for_each = length(var.ingress_rules) > 0 ? var.ingress_rules : []
content {
from_port = ingress.value.from_port
}
}
β Best Practices
- Use dynamic blocks only when necessary to reduce repetition
- Keep dynamic blocks simple - avoid complex nested logic
- Document dynamic blocks with comments explaining the iteration
- Use meaningful variable names for collections
- Test dynamic blocks with various input values
- Avoid deeply nested dynamic blocks - they reduce readability
- Use locals to simplify complex dynamic block logic
- Handle empty collections gracefully
- Use consistent naming for dynamic block variables
- Prefer static blocks when the structure is known and fixed
π Navigation
π Current Location: Dynamic Blocks (You are here)
β¬ οΈ Previous Step: Blocks
β‘οΈ Next Step: Provisioner
πΊοΈ Full Path: Introduction β Installation β Variables and Blocks β Provisioner
π Additional Resources
- π Dynamic Blocks Documentation: terraform.io/language/expressions/dynamic
- π For Each Expression: terraform.io/language/expressions/for
- π‘ Iteration Patterns: terraform.io/language/meta-arguments/for_each
- π Terraform Best Practices: terraform.io/cloud/guides
π Excellent! Dynamic Blocks Complete! π