'In Terraform, how do I repeat a dynamic block by an integer count?
I need to add multiple scratch_disk clauses to a resource for a Google Cloud VM.
I can use the following...
resource ... {
dynamic "scratch_disk" {
for_each = var.scratch_disk_count
content {
interface = "SCSI"
}
}
}
but then var.scratch_disk_count needs to be [ 1, 2, 3, 4 ] which looks a bit silly.
I tried replacing for_each with count = 4 but terraform said it didn't expect count there.
Is there a function to produce [ 1, 2, 3, 4 ] from 4, or just some generally better way?
This is a simple characterisation of the problem - I understand I could have the list be [ "SCSI", "SCSI", "NVME" ] or similar.
Thanks.
Solution 1:[1]
Yes you can use the range function for this:
resource ... {
dynamic "scratch_disk" {
for_each = range(var.scratch_disk_count)
content {
interface = "SCSI"
}
}
}
In your example above where the value of var.scratch_disk_count is 4, then the return of the range function will be [0, 1, 2, 3], and will produce the desired behavior. Note that it is also common to use the range function in dynamic blocks in this manner.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Schuchard |
