Execute local-exec conditionally within a for_each loop

I have a list of map objects that looks like this:

    variable "virtual_machines" {
      default = {
        "z-ca-bdc-control1" = {
           name          = "z-ca-bdc-control1"
           compute_node   = false
           etcd_instance = "etcd1"
           ipv4_address  = "192.168.113.88"
           ipv4_netmask  = "22"
           ipv4_gateway  = "192.168.112.1"
           dns_server    = "192.168.112.2"
           ram           = 8192
           logical_cpu   = 4
           os_disk_size  = 120
           px_disk_size  = 0
        },
        "z-ca-bdc-control12" =  {
           name          = "z-ca-bdc-control2"
           compute_node   = false
           etcd_instance = "etcd2"
           ipv4_address  = "192.168.113.89"
           ipv4_netmask  = "22"
           ipv4_gateway  = "192.168.112.1"
           dns_server    = "192.168.112.2"
           ram           = 8192
           logical_cpu   = 4
           os_disk_size  = 120
           px_disk_size  = 0
        },
        "z-ca-bdc-compute1" = {
           name          = "z-ca-bdc-compute1"
           compute_node   = true
           etcd_instance = "etcd3"
           ipv4_address  = "192.168.113.90"
           ipv4_netmask  = "22"
.
.
.
.

I know how to iterate around this using for_each, however, what I would like to do is to run a local-exec provisioner for all the map objects for which compute_node = false. If this is possible, how would this be done ?.

Hi @chrisadkin,

I think the most straightforward way to meet that requirement would be to have a local-exec provisioner active for all of your instances, but to make the script take no action when compute_node is false. For example:

  provisioner "local-exec" {
    command = (
      each.value.compute_node ?
      "command-to-run" :
      "/bin/true"
    )
  }

The above will make the command argument appear as /bin/true in the non-compute-node case, which should then succeed without doing anything assuming you’re running this on a typical Unix system.

1 Like

Thanks, that is a really elegant solution, I’ll go with that.