We close the HCL chapter with the tools that make your code smart and efficient: conditionals (making decisions) and loops (creating many resources without repeating yourself). Without them, you’d have to copy and paste the same block over and over. With them, you write once and Terraform generates whatever is needed.
The problem: don’t repeat yourself
Imagine you need three identical servers. Without loops, you’d write three almost identical resource blocks. If you needed to change something, you’d have to change it in all three. That’s tedious and error-prone.
Loops solve this: you declare the resource once and indicate “create it N times.” Let’s look at the tools.
count: create N copies
The count argument creates multiple copies of a resource. You give it a number and Terraform creates that many.
resource "aws_instance" "web" {
count = 3 # ← creates 3 instances
ami = "ami-0c1234567890abcde"
instance_type = "t3.micro"
tags = {
Name = "web-${count.index}" # web-0, web-1, web-2
}
}count = 3creates three instances.count.indexis the number of each copy (0, 1, 2), useful for giving them different names.
Analogy:
countis like telling a photocopier “make me 3 copies of this document.” All the same, numbered.
count is also useful for conditionals (create a resource or not):
resource "aws_instance" "bastion" {
count = var.create_bastion ? 1 : 0 # 1 if true, 0 if false
# ...
}If var.create_bastion is true, it creates 1; if it’s false, it creates 0 (none). This is a very common trick to make a resource “optional.”
for_each: create copies from a collection
The for_each argument creates a copy for each element of a map or set. Unlike count (which uses numbers), for_each uses meaningful keys.
resource "aws_instance" "server" {
for_each = {
web = "t3.micro"
api = "t3.small"
db = "m5.large"
}
ami = "ami-0c1234567890abcde"
instance_type = each.value # the value: t3.micro, t3.small, m5.large
tags = {
Name = each.key # the key: web, api, db
}
}- Creates one instance for each entry in the map.
each.keyis the key (web,api,db).each.valueis the value (t3.micro, etc.).
Analogy:
for_eachis like having a list of custom orders: “for web, a t3.micro; for api, a t3.small; for db, an m5.large.” Each with its own characteristics.
count vs for_each: which should I use?
This is an important decision and a typical source of confusion:
count |
for_each |
|
|---|---|---|
| Based on | A number | A map or a set |
| Identifies each copy by | Position (0, 1, 2…) | Meaningful key |
| Good for | Identical copies or optional resources | Resources with their own identity |
| Problem when deleting one in the middle | Reorders and may recreate others | Doesn’t affect the rest |
Practical rule:
- Use
countto create N identical copies or to make a resource optional (count = condition ? 1 : 0).- Use
for_eachwhen each resource has its own identity (different names, different configurations). It’s safer when adding or removing elements.Why
for_eachis usually preferred: withcount, if you delete the element in the middle of a list, the following ones “shift” and Terraform may destroy and recreate resources unnecessarily. Withfor_each, each resource is tied to its key, so removing one doesn’t affect the others. That’s why many professionals preferfor_eachexcept for simple cases.
The for expression: transforming collections
Don’t confuse the for_each loop (which creates resources) with the for expression (which transforms data). The for expression generates a new list or map from another, similar to a formula.
locals {
names = ["web", "api", "db"]
names_upper = [for n in local.names : upper(n)]
# result: ["WEB", "API", "DB"]
}Read it as: “for each n in the names list, return upper(n).” It’s a compact way to transform all elements of a collection.
Useful example: convert a list of names into a map, or filter elements that meet a condition. It’s an advanced tool you’ll see in real code, but at first it’s enough to recognize it.
Conditionals: the ternary operator
To make decisions within an expression, Terraform uses the ternary operator (the same as in many languages):
Examples:
instance_type = var.environment == "prod" ? "m5.large" : "t3.micro" # If the environment is "prod", use m5.large; otherwise, t3.micro count = var.high_availability ? 2 : 1 # If you want high availability, create 2; otherwise, 1
Analogy: it’s like saying “is it production? Then the big server; if not, the small one.” A quick decision in a single line.
A realistic example
variable "environment" {
type = string
default = "dev"
}
variable "subnets" {
type = map(string)
default = {
public-a = "10.0.1.0/24"
public-b = "10.0.2.0/24"
}
}
resource "aws_subnet" "this" {
for_each = var.subnets # one subnet per entry
vpc_id = aws_vpc.main.id
cidr_block = each.value # the range of each subnet
tags = {
Name = each.key # public-a, public-b
Type = var.environment == "prod" ? "production" : "development" # conditional
}
}This code creates one subnet for each entry in the subnets map (for_each loop), and tags each one according to the environment (ternary conditional). You wrote one block and Terraform generates as many subnets as you define, without repeating code.
What you should remember
count: creates N copies of a resource (count = 3) or makes it optional (count = condition ? 1 : 0). Identifies copies by position (count.index).for_each: creates a copy for each element of a map or set, with its own identity (each.key,each.value). Safer when adding/removing elements.- Rule:
countfor identical or optional copies;for_eachwhen each resource is different (usually preferable). - The
forexpression transforms collections (don’t confuse with thefor_eachloop). - The ternary operator
condition ? a : bmakes decisions in one line (ideal for differentiating environments).
With this, you’ve finished Chapter 10 and now know how to read and write HCL. In Chapter 11 we’ll look at two fundamental pieces for Terraform to work: providers (how it talks to AWS) and state (how it remembers what it has created).
Cloud, AWS & Terraform — From Zero to Expert
Chapter 1 · What is cloud computing
- 1.1 The traditional client-server model
- 1.2 Problems the cloud came to solve
- 1.3 On-premise vs cloud vs hybrid
- 1.4 The three service models: IaaS, PaaS, SaaS
- 1.5 The five pillars of cloud (according to NIST)
- 1.6 Real advantages: elasticity, pay-as-you-go, global availability
Chapter 2 · The cloud market and major providers
- 2.1 AWS, Azure and GCP: differences and market share
- 2.2 Why learn AWS first
- 2.3 Concepts that are universal among providers
Chapter 3 · Regions, availability zones and edge
- 3.1 What is an AWS region and how to choose it
- 3.2 Availability Zones: high availability by design
- 3.3 Edge locations and CloudFront
- 3.4 Latency, resilience and data sovereignty
Chapter 4 · Compute: EC2
- 4.1 Instances: types, families and when to choose each
- 4.2 AMIs, key pairs and Security Groups
- 4.3 Instance lifecycle
- 4.4 Elastic IPs and Placement Groups
- 4.5 Savings Plans vs Reserved vs On-Demand vs Spot
Chapter 5 · Storage: S3
- 5.1 Buckets, objects and keys
- 5.2 Storage classes (Standard, IA, Glacier…)
- 5.3 Versioning and object lifecycle
- 5.4 Bucket policies and ACLs
- 5.5 Static website hosting
Chapter 6 · Networking: VPC
- 6.1 What is a VPC and why you need it
- 6.2 Public and private subnets
- 6.3 Internet Gateway and NAT Gateway
- 6.4 Route Tables and Network ACLs
- 6.5 VPC Peering and endpoints
Chapter 7 · Identity and access: IAM
- 7.1 Users, groups, roles and policies
- 7.2 The principle of least privilege
- 7.3 Identity-based vs resource-based policies
- 7.4 MFA and temporary credentials (STS)
- 7.5 IAM security best practices
Chapter 8 · Managed databases
- 8.1 RDS: engines, Multi-AZ and read replicas
- 8.2 Aurora and its advantages over vanilla RDS
- 8.3 DynamoDB: key-value / document model
- 8.4 ElastiCache for in-memory cache
- 8.5 When to use each type of database
Chapter 9 · Why Infrastructure as Code
- 9.1 Problems with manual provisioning
- 9.2 Declarative vs imperative IaC
- 9.3 Terraform vs CloudFormation vs Pulumi vs CDK
- 9.4 The plan → apply → destroy cycle
Chapter 10 · HCL: the Terraform language
- 10.1 Resource, variable, output, locals blocks
- 10.2 Data types: string, number, bool, list, map, object
- 10.3 Expressions, references and built-in functions
- 10.4 Conditionals and loops (count, for_each, for)
Chapter 11 · Providers and state
- 11.1 How the AWS provider works
- 11.2 The terraform.tfstate file and its importance
- 11.3 Local state vs remote state (S3 + DynamoDB)
- 11.4 Essential commands: init, plan, apply, destroy, fmt, validate
Chapter 12 · Your first real infrastructure in Terraform
- 12.1 Create a VPC with subnets from scratch
- 12.2 Launch a public EC2 instance
- 12.3 Associate a Security Group and an Elastic IP
- 12.4 Outputs and references between resources
- 12.5 Team workflow: PR review of plans
Chapter 13 · Load balancing and auto scaling
- 13.1 Application Load Balancer vs Network Load Balancer
- 13.2 Target Groups, listeners and rules
- 13.3 Auto Scaling Groups: policies and metrics
- 13.4 Warm pools and lifecycle hooks
Chapter 14 · Serverless with Lambda
- 14.1 The Lambda execution model
- 14.2 Triggers: API Gateway, S3, DynamoDB Streams, SQS
- 14.3 Dependency management and layers
- 14.4 Cold starts and strategies to reduce them
- 14.5 Limits and anti-patterns
Chapter 15 · Messaging and events
- 15.1 SQS: standard vs FIFO queues, DLQ
- 15.2 SNS: topics, subscriptions, fan-out
- 15.3 EventBridge: event buses and rules
- 15.4 Patterns: pub/sub, decoupling, saga
Chapter 16 · Content delivery and DNS
- 16.1 Route 53: record types and routing policies
- 16.2 CloudFront: distributions, caches and origins
- 16.3 ACM: free SSL/TLS certificates
- 16.4 WAF integrated with CloudFront
Chapter 17 · Containers on AWS
- 17.1 Docker: quick review of key concepts
- 17.2 ECR: private image registry
- 17.3 ECS: task definitions, services, Fargate vs EC2
- 17.4 EKS: when Kubernetes and when not
Chapter 18 · Modules: reuse and composition
- 18.1 Anatomy of a Terraform module
- 18.2 Input variables, outputs and dependencies
- 18.3 Local modules vs Terraform Registry modules
- 18.4 Module versioning with Git tags
- 18.5 Design of generic vs domain-specific modules
Chapter 19 · Workspaces and environment management
- 19.1 Terraform workspaces: use cases and limitations
- 19.2 Directory strategy per environment (dev/stg/prod)
- 19.3 Terragrunt: DRY for environment configurations
- 19.4 Environment variables and .tfvars files
Chapter 20 · Remote backends and locking
- 20.1 Configure S3 + DynamoDB as backend
- 20.2 State locking: avoiding team corruption
- 20.3 State migration between backends
- 20.4 terraform import: bring existing resources into state
Chapter 21 · Infrastructure testing
- 21.1 Terraform validate and fmt in CI
- 21.2 Checkov and tfsec: static security analysis
- 21.3 Terratest: integration tests in Go
- 21.4 Contract testing between modules
Chapter 22 · Terraform in CI/CD
- 22.1 Basic pipeline: lint → plan → apply in GitHub Actions
- 22.2 Atlantis: GitOps for Terraform
- 22.3 Terraform Cloud / HCP Terraform
- 22.4 Drift detection and automatic reconciliation
Chapter 23 · Defense in depth
- 23.1 AWS Organizations and Service Control Policies
- 23.2 AWS Config: continuous compliance
- 23.3 GuardDuty: threat detection
- 23.4 Security Hub: centralized view
- 23.5 KMS: key management and rotation
- 23.6 Secrets Manager vs Parameter Store
Chapter 24 · Observability: logs, metrics and traces
- 24.1 CloudWatch Logs, metrics and alarms
- 24.2 CloudWatch Dashboards and Contributor Insights
- 24.3 X-Ray: distributed tracing
- 24.4 OpenTelemetry on AWS
- 24.5 Managed Grafana and Managed Prometheus
Chapter 25 · Cost optimization
- 25.1 AWS Cost Explorer and budgets with alerts
- 25.2 Trusted Advisor and Compute Optimizer
- 25.3 Rightsizing: how to detect overprovisioning
- 25.4 Savings Plans vs Reserved Instances: strategic decision
- 25.5 FinOps: culture and processes to control spending
Chapter 26 · High availability and disaster recovery
- 26.1 RTO and RPO: defining objectives
- 26.2 Strategies: backup/restore, pilot light, warm standby, multi-site
- 26.3 Route 53 health checks and automatic failover
- 26.4 AWS Backup: centralized backup policy
Chapter 27 · AWS Well-Architected Framework
- 27.1 The six pillars: operational excellence, security, reliability, performance efficiency, cost optimization, sustainability
- 27.2 Well-Architected Tool: formal reviews
- 27.3 How to apply the framework in design decisions
Chapter 28 · Serverless architectures at scale
- 28.1 Event-driven architecture with Lambda + EventBridge
- 28.2 Saga pattern for distributed transactions
- 28.3 Step Functions: orchestration of complex workflows
- 28.4 Lambda@Edge and CloudFront Functions
Chapter 29 · Data platforms on AWS
- 29.1 Data Lake with S3, Glue and Athena
- 29.2 Kinesis Data Streams and Firehose for streaming
- 29.3 Redshift: data warehousing at scale
- 29.4 Lake Formation: data governance
Chapter 30 · Multi-account and landing zones
- 30.1 Why separate workloads into different accounts
- 30.2 AWS Control Tower and Account Factory
- 30.3 Centralized log and security management
- 30.4 Terraform at multi-account scale with shared modules
Chapter 31 · Platform Engineering and Internal Developer Platform
- 31.1 Golden paths and abstractions over Terraform
- 31.2 AWS Service Catalog
- 31.3 Backstage as a developer portal
- 31.4 Terraform modules as internal product
Chapter 32 · Relevant AWS certifications
- 32.1 Cloud Practitioner: is it worth it?
- 32.2 Solutions Architect Associate → Professional
- 32.3 DevOps Engineer Professional
- 32.4 Specialty: Security, Database, Networking
- 32.5 HashiCorp Terraform Associate
Chapter 33 · Projects to consolidate what you've learned
- 33.1 Project 1: serverless blog (S3 + CloudFront + Lambda + DynamoDB)
- 33.2 Project 2: REST API with ECS Fargate + RDS + ALB
- 33.3 Project 3: data platform with Glue + Athena + Redshift
- 33.4 Project 4: multi-account landing zone with Terraform and Control Tower
