Mastering Loops and Conditionals in Terraform

Listen to this Post

Terraform, an Infrastructure as Code (IaC) tool, uses Hashicorp Configuration Language (HCL) to define and manage infrastructure. A key feature of HCL is its ability to handle loops and conditionals, which are essential for dynamic resource creation.

You Should Know:

1. Loops in Terraform (Count & For_Each)

Terraform provides two primary ways to loop through resources:
– `count` – Creates multiple instances of a resource.
– `for_each` – Iterates over a map or set to create resources.

Example: Using `count`

resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer-${count.index}"
}
}

This creates 3 EC2 instances with names WebServer-0, WebServer-1, and WebServer-2.

Example: Using `for_each`

variable "subnets" {
type = map
default = {
"subnet1" = "10.0.1.0/24"
"subnet2" = "10.0.2.0/24"
}
}

resource "aws_subnet" "example" {
for_each = var.subnets
cidr_block = each.value
vpc_id = aws_vpc.main.id
tags = {
Name = each.key
}
}

This dynamically creates subnets based on the `subnets` map.

2. Conditionals in Terraform

Use ternary expressions for conditional logic:

resource "aws_instance" "web" {
ami = var.env == "prod" ? "ami-prod123" : "ami-dev456"
instance_type = "t2.micro"
}

This selects the AMI based on the `env` variable.

3. Dynamic Blocks

For nested configurations (like security group rules), use `dynamic` blocks:

resource "aws_security_group" "example" {
name = "dynamic-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"]
}
}
}

This dynamically creates ingress rules based on the `ports` list.

4. Advanced: `for` Expressions

Filter and transform lists/maps:

output "instance_ips" {
value = [for instance in aws_instance.web : instance.private_ip]
}

This extracts private IPs from all instances.

What Undercode Say

Terraform’s loops and conditionals make infrastructure management scalable and dynamic. Key takeaways:
– Use `count` for numeric loops.
– Prefer `for_each` for complex iterations.
– Apply ternary operators for simple conditions.
– Leverage `dynamic` blocks for nested configurations.

Expected Output:

 Example: Deploying multiple EC2 instances with tags 
resource "aws_instance" "app_servers" {
for_each = toset(["app1", "app2", "app3"])
ami = "ami-0abcdef123456789"
instance_type = "t2.micro"
tags = {
Name = each.key
}
}

For further reading, check the original article: Mastering Loops and Conditionals in Terraform.

( extended with practical Terraform commands and examples.)

References:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image