How to generate blocks with different names

Hello everyone!
I want to enable Backups for GKE, a feature of the managed Kubernetes offering that Google Cloud has, via Terraform.

I’d have to add this to the cluster:

addons_config {
  gke_backup_agent_config {
    enabled = true
  }
}

Ideally, you would send a list of items you want enabled, when creating the cluster. Like:

addons_enabled = ["gke_backup_agent_config", "bla_bla", "some_other_feature"]

and the module should generate something like:

addons_config {
  gke_backup_agent_config {
    enabled = true
  }

  bla_bla {
    enabled = true
  }

  some_other_feature {
    enabled = true
  }
}

but I don’t know how I could generate that with Terraform

Dynamic Blocks - Configuration Language | Terraform | HashiCorp Developer generate blocks with the same name… not with the name of the item in a list…

This is the documentation of the specific configuration.

Thanks!

I don’t think what you want to do is feasible. Because the block identifiers change, you cannot use dynamic in this case.

It can be pretty annoying to work with nested blocks in resource definitions, e.g. the AWS WAFv2 WebACL resource. It’s just not possible to generate those blocks dynamically. See one way of working around that limitation.

Another thing you can do is to define all the blocks in your code and set the enabled value based on the result of a lookup, e.g.
contains(var.addons_enabled, "some_other_feature") ? true : false

The best though would be if the provider supported a resource type that allows you to create a single add-on attachment which you can reuse with for_each like aws_eks_addon

Thanks @macmiranda !
Maybe at some point Terraform will support such kind of dynamic blocks.
Until then, I think I’ll try something along the lines of this code, which is actually from Google

1 Like