0Pricing
Terraform Infrastructure as Code · Lesson

Dynamic Blocks for Nested Configuration

Generate repeated nested configuration blocks programmatically using dynamic blocks, eliminating copy-paste for things like security group rules.

The Repetition Problem

Some resources contain repeated nested blocks, such as multiple ingress rules in a security group. Writing each by hand is verbose and hard to keep DRY. Dynamic blocks generate them from a collection.

Static Blocks First

Here is the manual version: three near-identical ingress blocks. Imagine maintaining a dozen of these.

resource "aws_security_group" "web" {
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

All lessons in this course

  1. Using Loops with `for_each` and `count`
  2. Terraform Built-in Functions
  3. Conditional Expressions and Splats
  4. Dynamic Blocks for Nested Configuration
← Back to Terraform Infrastructure as Code