Which situation best justifies using a dynamic block over for_each in Terraform configuration?
Think about the difference between repeating nested blocks inside a resource versus creating multiple resources.
Dynamic blocks are used to generate repeated nested blocks inside a single resource or module block. for_each is used to create multiple instances of a resource or module.
You have a Terraform resource for a firewall that supports multiple security_rule nested blocks. You have a list of security rules to apply. Which approach correctly applies all rules inside a single firewall resource?
resource "firewall" "example" { name = "example-firewall" # Fill in here }
Remember that nested blocks inside a resource can be repeated with dynamic blocks.
Dynamic blocks allow you to generate multiple nested blocks inside a single resource. Using for_each on the resource creates multiple resources, which is not desired here.
Given the following Terraform snippet, what will be the value of resource.firewall.example.security_rule after apply?
variable "rules" { default = [ { name = "allow-ssh", port = 22 }, { name = "allow-http", port = 80 } ] } resource "firewall" "example" { name = "example-firewall" dynamic "security_rule" { for_each = var.rules content { name = each.value.name port = each.value.port } } }
Think about how dynamic blocks create nested blocks with full attributes.
The dynamic block creates two nested security_rule blocks with full attributes as objects in a list.
What is a potential security risk when using for_each to create multiple resources instead of using a dynamic block to create nested blocks inside a single resource?
Consider how multiple resources might be managed differently than one resource with nested blocks.
Creating multiple resources with for_each can lead to inconsistent updates or drift if some resources are changed and others are not, risking security policy gaps.
Consider a Terraform resource that uses both for_each on the resource itself and a dynamic block inside it to create nested blocks. What is the expected behavior after apply?
variable "instances" { default = ["one", "two"] } variable "rules" { default = [ { name = "rule1", port = 8080 }, { name = "rule2", port = 9090 } ] } resource "firewall" "example" { for_each = toset(var.instances) name = "firewall-${each.key}" dynamic "security_rule" { for_each = var.rules content { name = each.value.name port = each.value.port } } }
Think about how for_each on resource and dynamic blocks inside it combine.
The for_each on the resource creates two firewall resources. Each resource uses the dynamic block to create two nested security_rule blocks, so total four nested blocks across two resources.