Search code examples
terraformconditional-statements

Terraform How to execute a block conditionally


I'm learning Terraform and trying to use it for provisioning a virtual machine in Proxmox and came across a issue where I want to add a second disk only on the first index of the count.

I've try adding size = count.index == 0 ? "50G" : null on the disk block but it doesn't work as the size parameter expects a value.

Here is my code:

resource "proxmox_vm_qemu" "workers" {
  count       = 2
  name        = "${local.vm_worker_name}-${count.index + 1}"
  target_node = local.target_node
  vmid        = "21${count.index}"

  agent   = 1
  os_type = "linux"
  onboot  = true
  cores   = 4
  sockets = 1
  memory  = 4046
  scsihw  = "virtio-scsi-pci"
  tags    = local.vm_worker_tags

  disks {
    virtio {
      virtio0 {
        disk {
            size    = "15G"
            storage = "local-lvm"
            backup  = true  
        }
      }
      virtio1 {
        disk {
            size    = count.index == 0 ? "50G" : "0"
            storage = "local-lvm"
            backup  = true  
        }
      }      
    }
    ide {
        ide0 {
            cdrom {
                iso = local.talos_linux_iso
            }
        }      
    }
  }  

  network {
    id = 0
    model  = "virtio"
    bridge = "vmbr0"
    tag    = "100"
  }

  ipconfig0 = "ip=dhcp"
}

So, how can I use an if/else statement to accomplish this?


Solution

  • In this case, using the dynamic block with for_each could do the trick. For example:

    resource "proxmox_vm_qemu" "workers" {
      count       = 2
      name        = "${local.vm_worker_name}-${count.index + 1}"
      target_node = local.target_node
      vmid        = "21${count.index}"
    
      agent   = 1
      os_type = "linux"
      onboot  = true
      cores   = 4
      sockets = 1
      memory  = 4046
      scsihw  = "virtio-scsi-pci"
      tags    = local.vm_worker_tags
    
      disks {
        virtio {
         .
         .
         .
          
         dynamic "virtio1" {
           for_each = count.index == 0 ? [1] : []
           content {
             disk {
               size    = "50G"
               storage = "local-lvm"
               backup  = true  
             }
           }      
         }
        .
        .
        .
      }  
    
      .
      .
      .
    }
    

    However, I don't have a way to test this, so it may or may not work.