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.
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND