A security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?
IntermediateScenarioResources Variables and Expressions
Answer
Situation read → Repeated nested blocks: use dynamic.
What I'd do →
resource "aws_security_group" "app" {
name = "app"
vpc_id = var.vpc_id
dynamic "ingress" {
for_each = var.ingress_rules # map(object({port=number, cidrs=list(string)}))
content {
description = ingress.key
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidrs
}
}
}
Why → dynamic generates blocks from a collection. For larger rule sets, I prefer separate aws_vpc_security_group_ingress_rule resources so rules have their own state addresses.
Interview tip → Overusing dynamic hurts readability; use it only where the structure is genuinely variable.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced