A dynamic block lets you generate multiple nested blocks inside a resource or module based on a list or map. It helps avoid repeating similar blocks manually.
Click to reveal answer
beginner
Why use dynamic blocks in ingress rules?
Dynamic blocks allow you to create multiple ingress rules flexibly from a list of rules, making your Terraform code cleaner and easier to maintain.
Click to reveal answer
intermediate
How do you reference the current item inside a dynamic block?
Inside a dynamic block, you use the special variable each.value to access the current item from the list or map you are looping over.
Click to reveal answer
intermediate
Example syntax of a dynamic block for ingress rules?
A. Incorrect use of '=' after content instead of block
B. Missing quotes around "ingress"
C. for_each should be inside content block
D. cidr_blocks must be a string, not a list
Solution
Step 1: Check dynamic block syntax for content
The content block should be a block, not assigned with '='. Using '=' causes syntax error.
Step 2: Verify other parts
Quotes around "ingress" are present; for_each is correctly outside content; cidr_blocks accepts list.
Final Answer:
Incorrect use of '=' after content instead of block -> Option A
Quick Check:
content is a block, not an assignment [OK]
Hint: Use block syntax for content, not '=' assignment [OK]
Common Mistakes:
Using '=' after content instead of block braces
Placing for_each inside content
Omitting quotes around block type
5. You want to create ingress rules dynamically but only for rules where from_port is greater than 1000. Which Terraform expression correctly filters var.rules for use in a dynamic block's for_each?
hard
A. for_each = [for r in var.rules : r if r.from_port > 1000]
B. for_each = { for idx, r in var.rules : idx => r if r.from_port > 1000 }
C. for_each = filter(var.rules, r => r.from_port > 1000)
D. for_each = { for r in var.rules : r.from_port => r if r.from_port > 1000 }
Solution
Step 1: Understand for_each type requirements
for_each expects a map or set of strings; using a map with keys is preferred for dynamic blocks.
Step 2: Analyze each option
A returns a list, which is invalid for for_each in dynamic blocks. B uses r.from_port as key, which may duplicate keys. C uses filter function which is invalid syntax in Terraform. D creates a map with index keys filtered by condition, valid and safe.
Final Answer:
for_each = { for idx, r in var.rules : idx => r if r.from_port > 1000 } -> Option B
Quick Check:
for_each needs map with unique keys filtered by condition [OK]
Hint: Use map comprehension with index keys and condition [OK]
Common Mistakes:
Using list instead of map for for_each
Using non-unique keys causing errors
Trying unsupported filter() function
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.