Terraform's dynamic blocks allow you to create multiple resource configurations based on dynamic data or variables. This functionality helps you automate infrastructure provisioning for scenarios requiring repetitive blocks with variations.
Using Dynamic Blocks
A dynamic block is defined within a resource block and follows this structure:
resource "<resource_type>" "<resource_name>" {
# ... other resource configuration options
dynamic "<dynamic_block_name>" {
for_each = <expression_or_variable>
content {
# ... configuration options for each iteration
}
}
}
<dynamic_block_name>: A name for your dynamic block.for_each: This argument defines the collection to iterate over, which can be a list, map, or an expression that evaluates to a collection.content: This block defines the configuration for each iteration of the loop. You can access elements from thefor_eachcollection using attributes likekeyandvalue.
Example - Creating Web Servers with Dynamic Ports
Let's create web server instances with automatically assigned ports from a base port number:
variable "base_port" {
type = number
default = 8000
}
resource "null_resource" "web_servers" {
dynamic "server" {
for_each = range(3) # Creates 3 iterations (ports 8000, 8001, 8002)
content {
name = format("web-server-%d", dynamic.server.index + 1)
port = var.base_port + dynamic.server.index
# ... other web server configurations
}
}
}
Explanation:
variable "base_port"defines the starting port number.resource "null_resource"defines a resource with a dynamic block named "server".for_each = range(3): Therangefunction generates a list of numbers from 0 to 2, creating three iterations.dynamic.server.index: This attribute references the current index within the loop (0, 1, or 2).- The
contentblock defines configurations for each server instance:- The name is dynamically generated using
formatand the loop index. - The port is assigned by adding the
base_portto the loop index.
- The name is dynamically generated using
Benefits of Dynamic Blocks
- Reduced Code Duplication: Eliminates the need to write repetitive blocks for similar resources.
- Dynamic Configuration: Enables you to create configurations that vary based on input data or calculations.
- Improved Maintainability: Makes your code more concise and easier to manage.
Additional Considerations
- Dynamic blocks can be nested for more complex configurations.
- You can use conditional expressions within the
contentblock to create variations based on specific conditions.
By mastering dynamic blocks, you can write Terraform configurations that are flexible, adaptable, and efficient for provisioning infrastructure with multiple resources and variations.