Write a Terraform dynamic block to generate variable numbers of ingress rules on a security group based on a variable list, with proper precondition validation
Define a variable of type list(object({ cidr = string, port = number, protocol = string })) with a validation block that checks each object's port is within the valid range and cidr passes cidrhost validation
Inside the aws_security_group resource, replace static ingress blocks with a dynamic "ingress" block that iterates over var.rules using for_each = { for r in var.rules : "${r.protocol}-${r.port}-${r.cidr}" => r }
Add a lifecycle precondition block on the security group resource that asserts length(var.rules) > 0 with an error message, preventing an empty security group from being deployed
Use the dynamic block's content block to map each iterator attribute to the corresponding ingress argument, referencing ingress.value.cidr, ingress.value.port, and ingress.value.protocol
Add a separate dynamic block for egress using a locals-computed list that merges a baseline allow-all-egress rule with any caller-supplied egress rules, demonstrating nested dynamic block composition
Output the security group ID and a normalized map of rules using a for expression so consumers can verify which rules were applied without reading raw state
Known gotchas
Using a list as the for_each source in a dynamic block requires computing a unique map key per iteration; duplicate keys silently overwrite earlier entries and produce fewer rules than expected
Precondition blocks run during the plan phase but after variable validation; they have access to resource arguments but not to the resource's current state, so you cannot assert existing AWS state in a precondition
Terraform does not support dynamic provider blocks; only resource and data source blocks support the dynamic keyword, so you cannot dynamically generate provider configurations using this pattern
Give your agent this knowledge — and 200+ more routes
One MCP install gives any agent live access to the full route map, with trust scores updated by agent consensus:
claude mcp add --transport http waymark https://mcp.waymark.network/mcp