Skip to main content

Command Palette

Search for a command to run...

πŸ“˜ Terraform Series – Day 9

Published
β€’4 min read
πŸ“˜ Terraform Series – Day 9

Meta Arguments: count vs for_each with Output

πŸ“ Abstract

In Terraform, managing multiple resources efficiently is a common requirement in real-world DevOps projects. While creating multiple instances may seem straightforward, choosing the right approach can significantly impact scalability, flexibility, and maintainability.

This blog explores Terraform meta arguments, specifically count and for_each, and demonstrates how they behave differently when creating multiple resources. It also covers how outputs change based on these approaches and when to use depends_on for explicit dependencies.

🎯 Objectives

After completing this blog, you will be able to:

  • Understand what meta arguments are in Terraform

  • Create multiple resources using count

  • Identify limitations of count

  • Use for_each for better flexibility

  • Handle outputs correctly for both approaches

  • Understand the use of depends_on

πŸ”· Step 1: Understanding Meta Arguments

Meta arguments are special Terraform keywords that control resource behavior.

Common Meta Arguments:

  • count

  • for_each

  • depends_on

  • lifecycle

πŸ‘‰ In this tutorial, we focus on:

  • count

  • for_each

πŸ”· Step 2: Creating Multiple Resources using count

βœ… Code

resource "aws_instance" "my_instance" {
  count         = 2
  ami           = var.ec2_ami_id
  instance_type = var.ec2_instance_type
}

πŸ” Explanation

  • Terraform creates 2 EC2 instances

  • Indexed as:

aws_instance.my_instance[0]
aws_instance.my_instance[1]

πŸ”· Step 3: Output using count

output "ec2_public_ip" {
  value = aws_instance.my_instance[*].public_ip
}

🧠 Concept

  • [*] β†’ Splat Expression

  • Used to extract values from multiple resources

πŸ”· Step 4: Limitation of count

Using count has restrictions:

  • Same configuration for all instances

  • Cannot assign:

    • Different names ❌

    • Different instance types ❌

πŸ”· Step 6: Using for_each (Better Approach)

resource "aws_instance" "my_instance" {
  for_each = {
    Apurv-1 = "t2.micro"
    Apurv-2 = "t2.medium"
  }

  ami           = var.ec2_ami_id
  instance_type = each.value

  tags = {
    Name = each.key
  }
}

🧠 Explanation

  • each.key β†’ Instance Name

  • each.value β†’ Instance Type

πŸ‘‰ Each instance becomes unique and configurable

πŸ”· apply terraform and check output

terraform apply 

πŸ”· Step 7: Why Old Output Fails

πŸ’‘
In the above outputs, we get a list of Public IPs and DNS values. However, the issue is that Terraform only returns a list of values, and it does not clearly indicate which IP belongs to which instance.

❌ Old Code

aws_instance.my_instance[*].public_ip

❗ Reason

  • count β†’ returns list

  • for_each β†’ returns map

πŸ‘‰ So [*] does not work here

πŸ”· Step 8: Correct Output with for_each

βœ… Public IP

output "ec2_public_ip" {
  value = [
    for instance in aws_instance.my_instance :
    instance.public_ip
  ]
}

βœ… Public DNS

output "ec2_public_dns" {
  value = [
    for instance in aws_instance.my_instance :
    instance.public_dns
  ]
}

βœ… Private IP

output "ec2_private_ip" {
  value = [
    for instance in aws_instance.my_instance :
    instance.private_ip
  ]
}

πŸ”· Step 9: Final Result

After applying for_each:

  • Different instance names βœ…

  • Different instance types βœ…

  • Correct outputs fetched βœ…

πŸ”· Step 10: Understanding depends_on

βœ… Definition

depends_on is used to explicitly define dependencies

βš™οΈ Example

depends_on = [
  aws_security_group.my_groups,
  aws_key_pair.my_key
]

🧠 When to Use

  • When Terraform cannot detect dependency automatically

  • When using hardcoded values

  • When dependencies are indirect

❌ When NOT to Use

key_name = aws_key_pair.my_key.key_name

πŸ‘‰ Terraform automatically handles this (implicit dependency)

πŸš€ Conclusion

  • Use count β†’ for simple, identical resources

  • Use for_each β†’ for flexible and scalable setups

  • Understand difference between list vs map outputs

  • Use depends_on only when required

πŸ‘¨β€πŸ’» About the Author

β€œA complete Terraform series covering everything from fundamentals to advanced real-world infrastructure automation in a DevOps environment.”

πŸ“¬ Let's Stay Connected

Terraform

Part 3 of 11

πŸš€ Terraform Series – Automate Your Infrastructure Starting a complete **Terraform series** where I’ll cover everything from **basic to advanced level** with real-world practicals. In this series, you will learn: β€’ What is Infrastructure as Code (IaC) & why it matters β€’ Terraform fundamentals (providers, resources, state) β€’ Writing and managing Terraform configurations β€’ Variables, outputs & modules β€’ Remote state & state management β€’ Provisioning infrastructure on AWS β€’ Automation & real-world use cases β€’ Advanced concepts like workspaces, modules, and best practices 🎯 Goal: Help you automate infrastructure and become job-ready in DevOps. Perfect for **beginners, students, and DevOps learners** who want hands-on experience. Stay tuned and let’s build infrastructure the smart way βš‘πŸ’» #Terraform #DevOps #Cloud #AWS #InfrastructureAsCode #Automation

Up next

πŸ“˜ Terraform Series – Day 8

Automating AWS EC2 Setup with Terraform and user_data Welcome back to our Terraform journey. In infrastructure as code, setting up a server is just the beginning. After your EC2 instance is running, y