MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform dynamaic block details explaination with example

A Terraform dynamic block generates repeated nested blocks inside a resource, data source, provider or provisioner, such as ingress rules in a security group or rule blocks in an S3 lifecycle configuration. It does not create multiple resources. That is what count and for_each on the resource are for. This page fixes the invalid example above and walks through working, tested patterns: the dynamic block syntax, custom iterators, nested and conditional blocks, and common errors.

Terraform dynamic blocks are a way to dynamically generate Terraform configuration code based on the values of variables or maps. Dynamic blocks enable you to generate Terraform resources based on input values and make your configurations more flexible, reusable, and easier to manage.

Here’s an example to illustrate the use of dynamic blocks:

Let’s say you have a variable called count that defines the number of AWS S3 buckets that you want to create. The code below shows how you can use a dynamic block to generate the required number of S3 bucket resources based on the value of the count variable:


variable "count" {
  type = number
}

resource "aws_s3_bucket" "example" {
  count = var.count

  for_each = toset(var.count)
  
  dynamic "bucket" {
    for_each = var.count

    content {
      bucket = "bucket-${count.index}"
    }
  }
}
Code language: JavaScript (javascript)

In the example above, the dynamic block is used to generate the S3 bucket resources. The for_each argument is used to iterate over the values of the count variable and create a new S3 bucket resource for each iteration. The content block inside the dynamic block defines the configuration for each S3 bucket. The bucket argument inside the content block is using the count.index expression to generate a unique name for each S3 bucket resource.

Dynamic blocks allow you to generate Terraform configurations dynamically based on input values, making your configurations more flexible, reusable, and easier to manage.


Why the example above does not work

The code above fails at terraform validate for several reasons. Treat it as an example of what not to do. Each problem is listed here so you can spot the same mistakes in your own code.

Line in the exampleProblemFix
variable "count"count is a reserved name. Terraform rejects variables named count, for_each, source, version, providers, depends_on, lifecycle and locals.Use a name such as bucket_count or bucket_names.
count = var.count together with for_eachcount and for_each are mutually exclusive in the same resource.Choose one. Use for_each when each instance has a stable key.
toset(var.count)toset() takes a list, not a number.Pass a list(string) or set(string) variable.
dynamic "bucket"bucket is an argument of aws_s3_bucket, not a nested block, so there is nothing to generate. Dynamic blocks only produce nested blocks and never produce resources.Set bucket directly and repeat the resource with count or for_each.
bucket-${count.index}Inside a dynamic block you refer to the iterator (<label>.key and <label>.value). Also, S3 bucket names must be globally unique, so bucket-0 is almost certainly taken already.Use a unique prefix plus the key, for example ${var.prefix}-${each.key}.

Creating multiple S3 buckets correctly

To create several buckets you repeat the resource, not a block inside it. With for_each, each bucket gets a stable address such as aws_s3_bucket.this["logs"]. Removing one name from the set then destroys only that bucket. With count, removing an item from the middle of a list shifts the indexes of the items after it.

variable "bucket_prefix" {
  type        = string
  description = "Globally unique prefix, e.g. acme-prod"
}

variable "bucket_names" {
  type    = set(string)
  default = ["logs", "artifacts", "backups"]
}

resource "aws_s3_bucket" "this" {
  for_each = var.bucket_names
  bucket   = "${var.bucket_prefix}-${each.key}"
}

# Equivalent with count (index-based addresses):
# variable "bucket_count" { type = number }
# resource "aws_s3_bucket" "numbered" {
#   count  = var.bucket_count
#   bucket = "${var.bucket_prefix}-${count.index}"
# }Code language: PHP (php)

For a full comparison of count, for_each and for expressions, see Terraform Loops and Iteration.

Dynamic block syntax

dynamic "<nested_block_type>" {
  for_each = <list, set, map or object collection>
  iterator = <optional name, defaults to the block label>
  labels   = [<optional, for blocks that take labels>]

  content {
    # arguments of ONE nested block
    # use <iterator>.key and <iterator>.value
  }
}Code language: HTML, XML (xml)
  • Label ("ingress", "rule"): the type of nested block to generate. It must be a block that the resource schema supports.
  • for_each: any collection. Unlike resource-level for_each, a dynamic block accepts a plain list of objects, so you do not need to convert it to a map.
  • Iterator: a temporary symbol that is named after the label unless you set iterator. .key is the map key or list index, and .value is the current element.
  • content: the body of each generated block. You can nest further dynamic blocks inside it.
  • Dynamic blocks cannot generate meta-argument blocks such as lifecycle or provisioner.

Example: security group rules from a variable

This is the classic use case. Each rule in a variable becomes one ingress block. To add a port, you edit data rather than copying a block.

variable "vpc_id" {
  type = string
}

variable "ingress_rules" {
  type = list(object({
    description = string
    port        = number
    protocol    = string
    cidr_blocks = list(string)
  }))
  default = [
    { description = "HTTPS", port = 443, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] },
    { description = "SSH from office", port = 22, protocol = "tcp", cidr_blocks = ["203.0.113.0/24"] },
  ]
}

resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "Web server security group"
  vpc_id      = var.vpc_id

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

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}Code language: PHP (php)
terraform init
terraform validate
terraform plan -var="vpc_id=vpc-0123456789abcdef0"Code language: JavaScript (javascript)

The plan shows one security group with two ingress entries and ends with Plan: 1 to add, 0 to change, 0 to destroy. Add a third object to ingress_rules and the plan shows an in-place update to the same resource.

Note: Current AWS provider versions also offer separate aws_vpc_security_group_ingress_rule resources. Do not mix inline ingress blocks and standalone rule resources on the same security group, because they will overwrite each other.

Nested and conditional dynamic blocks

In AWS provider v4 and later, S3 lifecycle rules live in aws_s3_bucket_lifecycle_configuration. That makes it a good place to show a custom iterator, a nested dynamic block, and the condition ? [1] : [] pattern, which includes a block only when it is needed. The optional() type modifier requires Terraform 1.3 or later.

variable "lifecycle_rules" {
  type = list(object({
    id              = string
    prefix          = string
    expiration_days = number
    transition_days = optional(number) # null = no transition
  }))
  default = [
    { id = "app-logs", prefix = "app/", expiration_days = 365, transition_days = 30 },
    { id = "tmp", prefix = "tmp/", expiration_days = 7 },
  ]
}

resource "aws_s3_bucket_lifecycle_configuration" "logs" {
  bucket = aws_s3_bucket.this["logs"].id

  dynamic "rule" {
    for_each = var.lifecycle_rules
    iterator = lc               # custom iterator name

    content {
      id     = lc.value.id
      status = "Enabled"

      filter {
        prefix = lc.value.prefix
      }

      # Conditional block: zero or one transition
      dynamic "transition" {
        for_each = lc.value.transition_days == null ? [] : [lc.value.transition_days]
        content {
          days          = transition.value
          storage_class = "STANDARD_IA"
        }
      }

      expiration {
        days = lc.value.expiration_days
      }
    }
  }
}Code language: PHP (php)

The outer block uses the custom iterator lc, so the inner block can still use its default iterator transition without any ambiguity. The tmp rule gets no transition block at all. Custom iterators matter most when both levels would otherwise have the same name, or when the label is long.

Common errors and fixes

ErrorCauseFix
Unsupported block typeThe label is an argument, a misspelled block type, or a block the resource does not supportCheck the resource's argument reference in the provider docs
Unsupported attribute on each.value / count.indexUsing resource-level symbols inside contentUse <iterator>.value and <iterator>.key
Invalid variable nameDeclared a variable named count, for_each, source and so onRename the variable
The "count" and "for_each" meta-arguments are mutually-exclusiveBoth set on one resourceKeep only one
Invalid function argument from toset()Passed a number or mapPass a list, or use keys() or range()
Too many or missing blocksProvider expects at most one block (for example versioning_configuration)Use the cond ? [1] : [] pattern, not a list with many elements

Best practices

  • Use dynamic blocks when the number of nested blocks really varies with input. For two fixed blocks, writing them out literally is easier to read.
  • Give variables precise types (list(object({...}))) so mistakes fail at plan time instead of at the API.
  • Avoid deep nesting. More than two levels usually means the data should be reshaped with a for expression in locals first.
  • Prefer separate resources (for example per-rule security group resources) when you need independent lifecycle or ownership of each item.
  • Run terraform fmt and terraform validate in CI or with pre-commit hooks, and scan generated rules such as 0.0.0.0/0 ingress with tfsec.

Frequently asked questions

Can a Terraform dynamic block create multiple resources?

No. A dynamic block only generates nested blocks inside a single resource. To create several resources, use count or for_each on the resource itself.

What is the difference between for_each on a resource and for_each in a dynamic block?

Resource-level for_each creates multiple resource instances and requires a map or a set of strings. A dynamic block's for_each creates multiple nested blocks and accepts any collection, including a list of objects.

How do I add a block only when a condition is true?

Use a dynamic block with for_each = var.enabled ? [1] : []. An empty list produces no block, and a one-element list produces exactly one.

What does the iterator argument do in a dynamic block?

It renames the temporary variable used inside content, which is otherwise named after the block label. This is useful for nested dynamic blocks or long labels.

Can I use dynamic blocks for lifecycle or provisioner blocks?

No. Terraform processes meta-argument blocks such as lifecycle and provisioner before it evaluates expressions, so they cannot be generated dynamically.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Terraform Error Handing with Try Catch

Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates…

Read More

Terraform: Example Code for Create Multiple Azure Linux Vms

This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the count meta-argument. The VMs sit behind a load balancer…

Read More

Terraform Tools for Developer Productivity Master Guide

Tools, Workflow, Security, Testing, CI/CD, Automation, AI Assistance, Governance, and Production Best Practices Verified baseline: 5 September 2026Audience: Terraform developers, DevOps/SRE, platform/cloud engineers, module authors, DevSecOps teams, and engineering…

Read More

Terraform Conditional Expressions and Logic: Complete Guide with Examples

Terraform Conditional Expressions and Logic โ€” Summary Table # Concept Purpose Example Creates Resources? 1 Ternary operator Choose between two values var.env == “prod” ? “t3.large” :…

Read More

Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks

Terraform Loops and Iteration โ€” Summary Table # Option / Method Purpose Input Common use case Creates resources? 1 count Repeats a resource or module a specified…

Read More

Terraform Architecture and Components through diagram

Terraform Architecture & End-to-End Workflow This reference architecture covers the standard Terraform CLI workflow, including execution from a developer machine or CI/CD runner. It shows the relationship…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x