Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic block in terraform resource using a boolean value

Tags:

terraform

I am trying to create a dynamic block based on a variable (currently a bool). From my reading so far it seems the only options available to me are for_each and for (or a combination). I can't seem to use count as that is a resource level only function.

I believe for and foreach expect an iterable, so my best way should be to create one based on a for/if expression, although i'm not having much luck..

What would be the best way to achieve this?

Current code is:

dynamic "job_cluster" {
    for_each = [for cluster in ["true"] : [] if var.jobs[0].uses_existing_cluster]

    content {
      job_cluster_key = var.jobs[0].cluster.cluster_key
      new_cluster {
        #num_workers   = 2
        node_type_id  = data.databricks_node_type.smallest.id
    }
}

I don't get any error message with this approach, but it does not fire when the bool=true

like image 208
network_slayer Avatar asked Oct 11 '25 10:10

network_slayer


1 Answers

I am guessing that the real question here is how to code a conditional for a dynamic block based on a bool type value assigned to var.jobs[0].uses_existing_cluster. In that situation we can simply use a ternary to return a dummy list (acceptable type in for_each for dynamic blocks although not resources for reasons of state) for a true logical return, and an empty list for a false return to short-circuit evaluate lazily:

dynamic "job_cluster" {
  for_each = var.jobs[0].uses_existing_cluster ? ["this"] : []

  content {
    job_cluster_key = var.jobs[0].cluster.cluster_key
      new_cluster {
        #num_workers = 2
        node_type_id = data.databricks_node_type.smallest.id
      }
    }
  }
}

where I also fixed a couple missing terminating brackets above also. I assumed that the enumerable is not necessary as it is not being used to assign values in your question. Also, if you need multiple iterations for the dynamic block, then the range function is commonly used:

dynamic "job_cluster" {
  # two iterations
  for_each = var.jobs[0].uses_existing_cluster ? range(1) : []

  content {
    job_cluster_key = var.jobs[0].cluster.cluster_key
      new_cluster {
        #num_workers = 2
        node_type_id = data.databricks_node_type.smallest.id
      }
    }
  }
}
like image 78
Matt Schuchard Avatar answered Oct 16 '25 06:10

Matt Schuchard