Bird
Raised Fist0
Terraformcloud~5 mins

Why dynamic blocks reduce repetition in Terraform - Why It Works

Choose your learning style10 modes available
Introduction
When you write infrastructure code, you often repeat similar blocks for multiple items. Dynamic blocks let you write one block that repeats automatically, saving time and reducing errors.
When you need to create multiple similar resources or nested blocks with small differences.
When you want to avoid copying and pasting the same code many times.
When your infrastructure configuration depends on a list or map of values.
When you want your code to be easier to update and maintain.
When you want to reduce mistakes caused by manual repetition.
Config File - main.tf
main.tf
variable "security_group_rules" {
  type = list(object({
    type        = string
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
  }))
  default = [
    {
      type        = "ingress"
      from_port   = 80
      to_port     = 80
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    },
    {
      type        = "ingress"
      from_port   = 443
      to_port     = 443
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  ]
}

resource "aws_security_group" "example" {
  name        = "example-sg"
  description = "Example security group"

  dynamic "ingress" {
    for_each = [for rule in var.security_group_rules : rule if rule.type == "ingress"]
    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
}

This Terraform file defines a variable with a list of security group rules. The aws_security_group resource uses a dynamic block to create multiple ingress rules automatically from the list. This avoids writing each rule manually.

The dynamic block loops over the rules and inserts the content block for each one, making the code shorter and easier to maintain.

Commands
This command initializes the Terraform working directory. It downloads the AWS provider plugin and prepares Terraform to run.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized!
This command shows what Terraform will do based on the configuration. It previews the creation of the security group with multiple ingress rules from the dynamic block.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_security_group.example will be created + resource "aws_security_group" "example" { + description = "Example security group" + id = (known after apply) + name = "example-sg" + ingress { + cidr_blocks = ["0.0.0.0/0"] + from_port = 80 + protocol = "tcp" + to_port = 80 } + ingress { + cidr_blocks = ["0.0.0.0/0"] + from_port = 443 + protocol = "tcp" + to_port = 443 } } Plan: 1 to add, 0 to change, 0 to destroy.
This command applies the configuration and creates the security group with the ingress rules. The -auto-approve flag skips manual confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_security_group.example: Creating... aws_security_group.example: Creation complete after 2s [id=sg-0123456789abcdef0] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
→
-auto-approve - Automatically approve the apply without asking for confirmation
This command displays the current state of the created resources, showing the security group with its dynamically created ingress rules.
Terminal
terraform show
Expected OutputExpected
aws_security_group.example: id = sg-0123456789abcdef0 name = example-sg description = Example security group 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"] }
Key Concept

If you remember nothing else from this pattern, remember: dynamic blocks let you write one block that repeats for many items, reducing copy-paste and making your code cleaner.

Common Mistakes
Writing multiple static blocks instead of using a dynamic block
This causes repetitive code that is hard to update and prone to errors.
Use a dynamic block with for_each to generate repeated blocks automatically from a list or map.
Using dynamic blocks without filtering the list properly
Terraform may try to create blocks for unwanted items, causing errors or unexpected resources.
Filter the list in for_each to include only relevant items for the dynamic block.
Summary
Dynamic blocks in Terraform let you generate repeated nested blocks from a list or map.
They reduce manual repetition and make your code easier to maintain and update.
Use terraform init, plan, apply, and show commands to deploy and verify your dynamic block configuration.

Practice

(1/5)
1. What is the main benefit of using dynamic blocks in Terraform?
easy
A. They replace the need for variables in Terraform configurations.
B. They improve the speed of Terraform plan and apply operations.
C. They reduce repetition by generating multiple nested blocks automatically.
D. They allow Terraform to run without a backend configuration.

Solution

  1. Step 1: Understand the purpose of dynamic blocks

    Dynamic blocks let you create repeated nested blocks from a list or map without manually copying code.
  2. Step 2: Compare benefits

    This reduces repetition and keeps code clean and scalable, unlike options about speed, variables, or backend.
  3. Final Answer:

    They reduce repetition by generating multiple nested blocks automatically. -> Option C
  4. Quick Check:

    Dynamic blocks reduce repetition = C [OK]
Hint: Dynamic blocks create repeated blocks from lists automatically [OK]
Common Mistakes:
  • Thinking dynamic blocks speed up Terraform execution
  • Confusing dynamic blocks with variables
  • Believing dynamic blocks remove backend needs
2. Which of the following is the correct syntax to start a dynamic block in Terraform?
easy
A. dynamic "block_name" { for_each = var.list }
B. dynamic block_name { for_each = var.list }
C. dynamic block_name = var.list { }
D. dynamic "block_name" = var.list { }

Solution

  1. Step 1: Recall dynamic block syntax

    Dynamic blocks use the keyword dynamic followed by the block name in quotes, then a block with for_each.
  2. Step 2: Match syntax to options

    Only dynamic "block_name" { for_each = var.list } matches the correct syntax: dynamic "block_name" { for_each = var.list }.
  3. Final Answer:

    dynamic "block_name" { for_each = var.list } -> Option A
  4. Quick Check:

    Correct dynamic block syntax = D [OK]
Hint: Dynamic block name must be in quotes after keyword dynamic [OK]
Common Mistakes:
  • Omitting quotes around block name
  • Using equals sign instead of braces
  • Placing for_each outside the block
3. Given this Terraform snippet:
variable "ports" { default = [80, 443] }

resource "aws_security_group" "example" {
  name = "example"

  dynamic "ingress" {
    for_each = var.ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

How many ingress blocks will be created in the security group?
medium
A. Depends on AWS region
B. 1
C. 0
D. 2

Solution

  1. Step 1: Analyze the for_each list

    The variable ports contains two values: 80 and 443.
  2. Step 2: Count dynamic block iterations

    The dynamic block creates one ingress block per item in var.ports, so 2 blocks total.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    List length = number of blocks = 2 [OK]
Hint: Dynamic blocks create one nested block per list item [OK]
Common Mistakes:
  • Assuming only one block is created
  • Thinking AWS region affects block count
  • Confusing dynamic block with static block
4. Identify the error in this Terraform dynamic block snippet:
dynamic "egress" {
  for_each = var.rules
  content = {
    from_port   = egress.value.from
    to_port     = egress.value.to
    protocol    = "tcp"
  }
}
medium
A. Incorrect use of equals sign for content block
B. Missing quotes around block name "egress"
C. for_each must be outside the dynamic block
D. Variable var.rules cannot be used in dynamic blocks

Solution

  1. Step 1: Check dynamic block content syntax

    The content must be a block, not assigned with equals sign.
  2. Step 2: Identify correct syntax

    Correct syntax uses content { ... } without equals sign. The snippet incorrectly uses content = { ... }.
  3. Final Answer:

    Incorrect use of equals sign for content block -> Option A
  4. Quick Check:

    content block uses braces, no equals sign = B [OK]
Hint: Use content { } block, not content = { } [OK]
Common Mistakes:
  • Using equals sign with content
  • Placing for_each outside dynamic block
  • Misquoting block name
5. You want to create multiple lifecycle_rule blocks in an aws_s3_bucket resource using a dynamic block. Your variable is a map with keys as rule names and values as rule details. Which approach correctly uses dynamic blocks to reduce repetition and handle the map structure?
hard
A. Use for_each = var.rules and access each rule with lifecycle_rule.key only inside content block.
B. Use for_each = var.rules and access each rule with lifecycle_rule.value inside content block.
C. Use count = length(var.rules) and index into var.rules inside content block.
D. Manually write each lifecycle_rule block without dynamic blocks.

Solution

  1. Step 1: Understand dynamic block with map variable

    When using a map, for_each iterates over key-value pairs. The value is accessed with lifecycle_rule.value.
  2. Step 2: Identify correct usage

    Use for_each = var.rules and access each rule with lifecycle_rule.value inside content block. correctly uses for_each = var.rules and accesses lifecycle_rule.value inside the content block to get rule details.
  3. Final Answer:

    Use for_each = var.rules and access each rule with lifecycle_rule.value inside content block. -> Option B
  4. Quick Check:

    Map iteration uses .value for content = A [OK]
Hint: Use .value to access map values inside dynamic block content [OK]
Common Mistakes:
  • Using only .key without .value for map data
  • Using count instead of for_each for maps
  • Writing blocks manually instead of dynamic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard