Terraform dynamaic block details explaination with example

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}"
    }
  }
}

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.

Rajesh Kumar
Follow me
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x