0
0
Terraformcloud~30 mins

Dynamic blocks vs for_each decision in Terraform - Hands-On Comparison

Choose your learning style9 modes available
Dynamic blocks vs for_each decision
📖 Scenario: You are managing cloud infrastructure using Terraform. You need to create multiple security group rules for a virtual network. Some rules are fixed, but others depend on a list of IP addresses that can change. You want to learn how to decide between using dynamic blocks and for_each to manage these rules efficiently.
🎯 Goal: Build a Terraform configuration that creates a security group with fixed rules and additional rules generated dynamically from a list of IP addresses. Learn when to use dynamic blocks versus for_each in Terraform.
📋 What You'll Learn
Create a security group resource with fixed ingress rules
Define a variable list of IP addresses for additional ingress rules
Use a dynamic block to add ingress rules from the IP list
Use for_each to create multiple security group rules from the IP list
Understand the difference between dynamic blocks and for_each in Terraform
💡 Why This Matters
🌍 Real World
Managing cloud security groups often requires adding multiple rules that can change over time. Using dynamic blocks and for_each helps automate and scale these configurations.
💼 Career
Cloud engineers and DevOps professionals use Terraform to manage infrastructure as code. Knowing how to decide between dynamic blocks and for_each is essential for writing clean, maintainable Terraform code.
Progress0 / 4 steps
1
Create a security group with fixed ingress rules
Write a Terraform resource called aws_security_group named example_sg with a fixed ingress rule allowing TCP port 80 from CIDR block 0.0.0.0/0.
Terraform
Need a hint?

Use the resource block with aws_security_group and add an ingress block with the specified port and CIDR.

2
Define a variable list of IP addresses
Create a Terraform variable called extra_ips of type list(string) with the default value ["10.0.0.1/32", "10.0.0.2/32"].
Terraform
Need a hint?

Use the variable block with type = list(string) and set the default list as shown.

3
Add ingress rules using a dynamic block
Inside the aws_security_group.example_sg resource, add a dynamic block named ingress that iterates over var.extra_ips. For each IP, create an ingress rule allowing TCP port 22 from that IP.
Terraform
Need a hint?

Use a dynamic block with for_each = var.extra_ips and inside content, define the ingress rule using ingress.value for the CIDR.

4
Create multiple security group rules using for_each
Create a separate resource aws_security_group_rule named extra_rules that uses for_each = toset(var.extra_ips). For each IP, create an ingress rule allowing TCP port 22 in the security group aws_security_group.example_sg.
Terraform
Need a hint?

Create a separate aws_security_group_rule resource with for_each = toset(var.extra_ips). Use each.key for the CIDR block and link to the security group ID.