0
0
Terraformcloud~15 mins

Why dynamic blocks reduce repetition in Terraform - Why It Works This Way

Choose your learning style9 modes available
Overview - Why dynamic blocks reduce repetition
What is it?
Dynamic blocks in Terraform let you write a block of configuration once and repeat it multiple times with different values. Instead of copying and pasting similar blocks, you use dynamic blocks to generate them automatically. This makes your code shorter, cleaner, and easier to change. It helps Terraform create multiple resources or settings based on a list or map.
Why it matters
Without dynamic blocks, you would write many repeated blocks manually, which is slow and error-prone. If you want to change something, you must update every copy, risking mistakes. Dynamic blocks solve this by generating repeated parts automatically, saving time and reducing bugs. This makes managing infrastructure more reliable and scalable.
Where it fits
Before learning dynamic blocks, you should understand basic Terraform blocks and how to write resource configurations. After mastering dynamic blocks, you can explore Terraform modules and advanced looping techniques to build reusable and flexible infrastructure code.
Mental Model
Core Idea
Dynamic blocks let Terraform write repeated configuration parts automatically from data, so you avoid copying the same code many times.
Think of it like...
Imagine you want to send the same invitation to many friends. Instead of writing each letter by hand, you create a template and fill in each friend's name automatically. Dynamic blocks do the same for Terraform code.
Terraform Configuration
┌───────────────────────────────┐
│ Resource Block                │
│ ┌───────────────────────────┐│
│ │ Static Configuration      ││
│ └───────────────────────────┘│
│ ┌───────────────────────────┐│
│ │ Dynamic Block (loop)      ││
│ │ ┌───────────────────────┐││
│ │ │ Repeated Sub-blocks    │││
│ │ └───────────────────────┘││
│ └───────────────────────────┘│
└───────────────────────────────┘
Build-Up - 7 Steps
1
FoundationBasic Terraform Block Structure
🤔
Concept: Learn how Terraform uses blocks to define resources and their settings.
Terraform uses blocks like resource, provider, and variable to organize configuration. Each block has a type and contains settings inside curly braces. For example, a resource block defines a cloud resource with its properties.
Result
You can write simple Terraform code to create one resource with fixed settings.
Understanding blocks is essential because dynamic blocks generate repeated blocks inside these basic structures.
2
FoundationManual Repetition in Terraform
🤔
Concept: See how repeating similar blocks manually leads to long and error-prone code.
If you want to create multiple similar sub-blocks, like multiple tags or rules, you write each one separately. For example, writing multiple ingress rules in a security group requires copying the block for each rule.
Result
Terraform code becomes long and hard to maintain when many similar blocks are repeated.
Recognizing manual repetition shows why automation with dynamic blocks is valuable.
3
IntermediateIntroducing Dynamic Blocks Syntax
🤔Before reading on: do you think dynamic blocks replace entire resources or just parts inside resources? Commit to your answer.
Concept: Dynamic blocks generate repeated nested blocks inside a resource or module using a loop over a list or map.
A dynamic block uses the keyword dynamic followed by the block type. Inside, you specify for_each to loop over data and content to define the block's body. Terraform creates one block per item in the loop.
Result
You write one dynamic block, and Terraform creates many repeated blocks automatically.
Knowing dynamic blocks generate nested blocks inside resources helps you write DRY (Don't Repeat Yourself) code.
4
IntermediateUsing for_each with Dynamic Blocks
🤔Before reading on: do you think for_each in dynamic blocks accepts only lists, or can it handle maps too? Commit to your answer.
Concept: for_each in dynamic blocks can loop over lists or maps to create blocks with different values.
You can pass a list or map to for_each. Inside content, you use each.value or each.key to access data. This lets you customize each generated block based on the input data.
Result
Dynamic blocks become flexible and powerful, adapting to different input shapes.
Understanding for_each's flexibility unlocks dynamic blocks' full potential for complex configurations.
5
IntermediateReplacing Repeated Static Blocks with Dynamic Blocks
🤔Before reading on: do you think dynamic blocks always reduce code length, or can they sometimes add complexity? Commit to your answer.
Concept: Dynamic blocks replace multiple repeated static blocks, reducing code duplication and improving maintainability.
Instead of writing many similar blocks, you write one dynamic block with a loop. This reduces lines of code and makes updates easier because you change the loop data, not each block.
Result
Terraform code is shorter, cleaner, and easier to update.
Knowing when to replace repetition with dynamic blocks improves code quality and reduces errors.
6
AdvancedDynamic Blocks in Complex Nested Structures
🤔Before reading on: do you think dynamic blocks can be nested inside other dynamic blocks? Commit to your answer.
Concept: Dynamic blocks can be nested to generate deeply nested repeated blocks in complex resources.
Some resources have nested blocks inside nested blocks. You can use dynamic blocks inside other dynamic blocks to generate these layers automatically, handling complex configurations like multiple rules with multiple conditions.
Result
You can automate very complex and repetitive Terraform configurations.
Understanding nested dynamic blocks helps manage complex infrastructure with less manual code.
7
ExpertPerformance and State Implications of Dynamic Blocks
🤔Before reading on: do you think dynamic blocks affect Terraform state size or plan time? Commit to your answer.
Concept: Dynamic blocks impact how Terraform plans and stores state, affecting performance and change detection.
Each generated block is tracked in Terraform state. Large loops create many state entries, which can slow plan and apply. Also, changes in loop data can cause many resource updates. Experts balance dynamic block use with performance considerations.
Result
You write efficient Terraform code that scales well and avoids slow operations.
Knowing dynamic blocks' impact on state and plan helps prevent performance bottlenecks in large infrastructures.
Under the Hood
Terraform parses the dynamic block and evaluates the for_each expression during the plan phase. For each item, it generates a separate nested block in the resource configuration. These generated blocks are treated like static blocks in the resource schema. Terraform tracks each generated block's state separately, allowing precise updates and deletions.
Why designed this way?
Dynamic blocks were introduced to solve the problem of repetitive code without changing Terraform's core resource schema. They allow flexible generation of nested blocks without requiring providers to support complex looping natively. This design keeps Terraform's language simple while enabling powerful automation.
Terraform Processing Flow
┌───────────────────────────────┐
│ Terraform Configuration File   │
│ ┌───────────────────────────┐ │
│ │ Resource Block            │ │
│ │ ┌───────────────────────┐ │ │
│ │ │ Dynamic Block          │ │ │
│ │ │ for_each = [items]     │ │ │
│ │ │ content { ... }        │ │ │
│ │ └───────────────────────┘ │ │
│ └───────────────────────────┘ │
└───────────────┬───────────────┘
                │ Evaluate for_each
                ▼
┌───────────────────────────────┐
│ Generated Nested Blocks        │
│ ┌─────────┐ ┌─────────┐       │
│ │ Block 1 │ │ Block 2 │ ...   │
│ └─────────┘ └─────────┘       │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do dynamic blocks create new resources or just nested blocks inside resources? Commit to your answer.
Common Belief:Dynamic blocks create new resources automatically for each item in the loop.
Tap to reveal reality
Reality:Dynamic blocks only generate repeated nested blocks inside a single resource, not separate resources.
Why it matters:Confusing this leads to wrong expectations about resource counts and can cause incorrect Terraform plans.
Quick: Can dynamic blocks be used anywhere in Terraform configuration? Commit to your answer.
Common Belief:You can use dynamic blocks anywhere, including top-level resource blocks or variables.
Tap to reveal reality
Reality:Dynamic blocks only work inside resource or module blocks where nested blocks are allowed.
Why it matters:Trying to use dynamic blocks in unsupported places causes syntax errors and confusion.
Quick: Do dynamic blocks always make Terraform code simpler? Commit to your answer.
Common Belief:Dynamic blocks always reduce complexity and make code easier to read.
Tap to reveal reality
Reality:Dynamic blocks can sometimes make code harder to understand if overused or nested deeply.
Why it matters:Overusing dynamic blocks can reduce code clarity and increase debugging difficulty.
Quick: Do dynamic blocks automatically handle all edge cases in resource schemas? Commit to your answer.
Common Belief:Dynamic blocks automatically adapt to any resource schema without extra work.
Tap to reveal reality
Reality:Dynamic blocks require careful matching of the resource schema and sometimes manual adjustments.
Why it matters:Misusing dynamic blocks can cause Terraform apply failures or unexpected behavior.
Expert Zone
1
Dynamic blocks do not create separate resources, so their lifecycle is tied to the parent resource, affecting update and destroy behavior.
2
Using dynamic blocks with complex for_each expressions can cause subtle state drift if the input data changes order or keys unexpectedly.
3
Terraform's plan output shows generated blocks as separate entries, which can confuse users unfamiliar with dynamic blocks' internal expansion.
When NOT to use
Avoid dynamic blocks when the repeated elements are better modeled as separate resources or modules, especially if they require independent lifecycle management. Use modules or count/for_each on resources instead.
Production Patterns
In production, dynamic blocks are often used to generate multiple security group rules, tags, or nested configuration blocks like listener rules in load balancers. Teams combine dynamic blocks with variables and locals to build flexible, reusable infrastructure templates.
Connections
Template Engines
Dynamic blocks are similar to template loops that generate repeated content from data.
Understanding how template engines loop over data to produce repeated output helps grasp how dynamic blocks automate repeated Terraform code.
Database Normalization
Dynamic blocks reduce repetition in code like normalization reduces data duplication in databases.
Both concepts aim to avoid repeated manual entries, improving maintainability and reducing errors.
Factory Design Pattern (Software Engineering)
Dynamic blocks act like a factory that creates multiple similar objects (blocks) from input data.
Seeing dynamic blocks as a factory helps understand their role in automating creation of repeated configuration parts.
Common Pitfalls
#1Writing repeated static blocks instead of using dynamic blocks.
Wrong approach:resource "aws_security_group" "example" { 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"] } ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["10.0.0.0/16"] } }
Correct approach:resource "aws_security_group" "example" { dynamic "ingress" { for_each = [ { from = 80, to = 80, cidr = "0.0.0.0/0" }, { from = 443, to = 443, cidr = "0.0.0.0/0" }, { from = 22, to = 22, cidr = "10.0.0.0/16" } ] content { from_port = ingress.value.from to_port = ingress.value.to protocol = "tcp" cidr_blocks = [ingress.value.cidr] } } }
Root cause:Not knowing dynamic blocks exist or how to use them leads to manual repetition.
#2Using dynamic blocks outside allowed places causing syntax errors.
Wrong approach:dynamic "variable" { for_each = ["a", "b"] content { value = variable.value } }
Correct approach:variable "example" { type = list(string) default = ["a", "b"] } resource "aws_example" "test" { dynamic "setting" { for_each = var.example content { value = setting.value } } }
Root cause:Misunderstanding where dynamic blocks are valid in Terraform syntax.
#3Overusing nested dynamic blocks making code hard to read.
Wrong approach:resource "aws_complex" "example" { dynamic "outer" { for_each = var.outer_list content { dynamic "middle" { for_each = outer.value.middle_list content { dynamic "inner" { for_each = middle.value.inner_list content { value = inner.value } } } } } } }
Correct approach:Split complex nested structures into modules or flatten data structures to reduce nesting, using dynamic blocks only where clarity is maintained.
Root cause:Trying to automate everything with dynamic blocks without considering code readability.
Key Takeaways
Dynamic blocks automate repeated nested blocks inside Terraform resources, reducing manual repetition.
They use for_each loops over lists or maps to generate multiple blocks from data.
Dynamic blocks improve code maintainability but can add complexity if overused or nested deeply.
They do not create separate resources but generate parts inside a resource's configuration.
Understanding dynamic blocks helps write cleaner, scalable, and more flexible Terraform infrastructure code.