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 list of items, and you want to generate a block for each item in the list.
Here’s a simple use case to illustrate the use of dynamic blocks:
Let’s say you have a list of security group rules, and you want to create Azure Security Group rules using Terraform. The rules are defined by a list of objects, where each object contains the details of a rule.
Azure Security Group with Dynamic Block
// main.tf
resource "azurerm_resource_group" "example" {
name = "example-resources1"
location = "West Europe"
}
provider "azurerm" {
features {}
subscription_id = "491e1121-c626-4***"
tenant_id = "2047b1bd-994d-4366-9d343****"
client_id = "a78d2362-7c1d-475b634019705***"
client_secret = "aSR8Q~UzW_2fWfpMnAHLnY~04qdEl~****"
}
resource "azurerm_network_security_group" "example" {
name = "acceptanceTestSecurityGroup1"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
dynamic "security_rule"{
for_each = var.virtual_network_rules
content {
name = security_rule.value["name"]
priority = security_rule.value["priority"]
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
tags = {
environment = "Production"
}
}
//Variables.tf
variable "virtual_network_rules" {
type = list(object({
name = string
priority = number
}))
}
//dev.tfvars
virtual_network_rules = [
{
name = "rule-1"
priority = 101
},
{
name = "rule-1"
priority = 101
}]
Commands to execute the Terraform modules
change to the directory
terraform init
terraform plan -var-file=/home/azureuser/Terraform-Repo/module-project-practice/dev.tfvarsterraform apply -var-file=/home/azureuser/Terraform-Repo/module-project-practice/dev.tfvars
Screenshot Reference for the folder Structure
Results