Monday, September 9, 2019

Dynamic Optional Block in Terraform 0.12

Having moved recently all our terraform code to version 0.12, I was quite happy to use the new dynamic block feature. It is basically aimed at creating dynamically repeatable blocks, but I discovered recently that it can also be used for optional blocks. The trick is to create a list that can have a size of zero or one.

For instance, I have a module that can create DNS entries in Route 53 in AWS. The resource aws_route53_record contains an optional alias block that I want to use only when the user defines the alias_dns_name input variable. I can simply create a list from this variable:

locals { alias_list = compact([var.alias_dns_name]) } resource "aws_route53_record" "dns" { ... dynamic "alias" { for_each = local.alias_list content { name = var.alias_dns_name zone_id = var.alias_zone_id evaluate_target_health = true } } }