Menu

Terraform dynamic blocks

DEV Community: terraform·Bartłomiej Danek·7 months ago
#WJIxxfaT
#dev#class#code#highlight#value
Reading 0:00
15s threshold

Terraform dynamic blocks

dynamic generates repeated nested blocks from a variable - avoids copy-pasting the same block for each item.

variable "ingress_rules" { default = [ { port = 80 , protocol = "tcp" , cidr = "0.0.0.0/0" }, { port = 443 , protocol = "tcp" , cidr = "0.0.0.0/0" }, { port = 22 , protocol = "tcp" , cidr = "10.0.0.0/8" }, ] }

resource "aws_security_group" "web" { name = "web"

dynamic "ingress" { for_each = var . ingress_rules content { from_port = ingress . value . port to_port = ingress . value . port protocol = ingress . value . protocol cidr_blocks = [ ingress . value . cidr ] } } }

iterator name

By default the iterator is the block label ( ingress above). Override it with iterator :

dynamic "ingress" { for_each = var . ingress_rules iterator = rule content { from_port = rule . value . port to_port = rule . value . port protocol = rule . value .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.