Course outlines for learning terraform.
expected time | requirements |
---|---|
45 minutes | A computer with Terraform installed, terraform knowledge. |
Goal: See how you may use Terraform dynamic blocks.
Sometimes you want to loop over a list and repeat a “block”. For example tcp-ports that should be allowed to access a resource.
This can be a challenge because the looping need to happen in a resource. Think if this example:
resource "x" "y" {
name = "my-thing"
allow {
port = 80
}
allow {
port = 443
}
}
It’s anoying to repeat this allow
block. Dynamic blocks to the rescue!
With the resource
and variable
s as described above, you can use a dynamic block:
variable "allow" {
default = [
{
port = 80
},
{
port = 443
}
]
}
resource "x" "y" {
name = "my-thing"
dynamic "allow" {
for_each = var.allow
content {
port = allow.value.port
}
}
}
Dynamic blocks are required from time to time, but a person less terraform-skilled may find this construct difficult to understand.
You can use blocks-in-blocks, making the code even harder to read.
Have a look here.
dynamic block
.dynamic_block
.dynamic block
?