Complete the code to define a dynamic block for ingress rules in Terraform.
dynamic "ingress" { for_each = var.ingress_rules content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.[1] } }
The cidr_blocks attribute specifies the IP ranges allowed in the ingress rule. It must match the variable key used in the ingress value.
Complete the code to iterate over ingress rules using a dynamic block.
resource "aws_security_group" "example" { name = "example" description = "Example security group" dynamic "ingress" { for_each = [1] content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.cidr_blocks } } }
The for_each must iterate over the variable containing ingress rules, which is var.ingress_rules.
Fix the error in the dynamic block by completing the missing attribute.
dynamic "ingress" { for_each = var.ingress_rules content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.[1] } }
The correct attribute name is cidr_blocks (plural), which expects a list of CIDR ranges.
Fill both blanks to create a dynamic ingress block with a condition to only include rules with protocol 'tcp'.
dynamic "ingress" { for_each = { for idx, rule in var.ingress_rules : idx => rule if rule.[1] == "[2]" } content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.cidr_blocks } }
The filter uses protocol to check if it equals tcp, so only TCP ingress rules are included.
Fill all three blanks to define a dynamic ingress block that filters rules with from_port greater than 1024 and protocol 'udp', and maps the port to 'to_port'.
dynamic "ingress" { for_each = { for idx, rule in var.ingress_rules : idx => rule if rule.[1] > [2] && rule.[3] == "udp" } content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.cidr_blocks } }
The filter checks if from_port is greater than 1024 and if protocol equals 'udp'.