Dynamic blocks in Terraform are used when you want to generate multiple instances of a block within a resource or module dynamically. This is particularly useful when you have a variable number of similar configurations to define. One common use case for dynamic blocks is when you’re working with a map of objects, and you want to generate a block for each object in the map.
Here’s a simple use case to illustrate the use of dynamic blocks:
Let’s say you have a map of objects consists of routing rules, and you want to create Azure Front door Routing rules using Terraform. The rules are defined by a object of maps, where each map object contains the details of a routing rule.
Azure Front Door with Dynamic Block
// main.tf
dynamic "routing_rule" {
for_each = var.routing_rule
content {
name = routing_rule.value.name
accepted_protocols = routing_rule.value.accepted_protocols
patterns_to_match = routing_rule.value.patterns_to_match
frontend_endpoints = routing_rule.value.frontend_endpoints
dynamic "forwarding_configuration" {
for_each = routing_rule.value.configuration == "Forwarding" ? [routing_rule.value.forwarding_configuration] : []
content {
forwarding_protocol = routing_rule.value.forwarding_configuration.forwarding_protocol
backend_pool_name = routing_rule.value.forwarding_configuration.backend_pool_name
}
}
}
}
// variables.tf
variable "routing_rule"{
type = Map(object())
description = "This is name of the location"
}
// terraform.tfvars
routing_rule = {
rr1 = {
name = "exampleRoutingRule1"
frontend_endpoints = ["exampleFrontendEndpoint1"]
accepted_protocols = ["Http", "Https"]
patterns_to_match = ["/*"]
enabled = true
configuration = "Forwarding"
forwarding_configuration = {
backend_pool_name = "exampleBackendBing1"
cache_enabled = false
cache_use_dynamic_compression = false
cache_query_parameter_strip_directive = "StripAll"
forwarding_protocol = "HttpsOnly"
}
redirect_configuration = {
custom_host = ""
redirect_protocol = "MatchRequest"
redirect_type = "Found"
custom_fragment = ""
custom_path = ""
custom_query_string = ""
}
}
}
Commands to execute the Terraform modules
change to the directory
terraform init
terraform plan -var-file=/home/azureuser/Terraform-Repo/module-project-practice/dev.tfvars
terraform apply -var-file=/home/azureuser/Terraform-Repo/module-project-practice/dev.tfvars
Screenshot Reference for the folder Structure