network_slayer
network_slayer

Reputation: 81

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

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

Upvotes: 4

Views: 6180

Answers (2)

Marko E
Marko E

Reputation: 18203

If the variable you have is only a simple bool value then it should be pretty simple:

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

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

Upvotes: 4

Matthew Schuchard
Matthew Schuchard

Reputation: 28854

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
      }
    }
  }
}

Upvotes: 5

Related Questions