I use terraform-libvirt for my homelab so i searched same answer.
My solution:
first of all i decided to add "running" variable and change in to true o false as i need, but it didn't work.
Then i added null-resource with if-else condition and it worked:
- add variable
variable "vm_condition_poweron" {
default = true
}
- Put it in
resource "libvirt_domain" "domain-name"
block:
resource "libvirt_domain" "domain-ubuntu" {
running = var.vm_condition_poweron
count = length(local.vm_common_list_count)
name = "${local.vm_common_list_count[count.index]}"
- Create null-resource
resource "null_resource" "shutdowner" {
# iterate with for_each over Vms list ( my *.tf file creates VMs from list)
for_each = toset(local.vm_common_list_count)
triggers = {
trigger = var.vm_condition_poweron
}
provisioner "local-exec" {
command = var.vm_condition_poweron?"echo 'do nothing'":"virsh -c qemu:///system shutdown ${each.value}"
}
}
- or you can create simpler nul_resource ( if you do not use lists for example), but it will shutdown all VMs on your host, not only created by this terraform
resource "null_resource" "shutdowner" {
triggers = {
trigger = var.vm_condition_poweron
}
provisioner "local-exec" {
command = var.vm_condition_poweron?"echo 'do nothing'":"for i in $(virsh -c qemu:///system list --all|tail -n+3|awk '{print $2}'); do virsh -c qemu:///system shutdown $i; done"
}
}
- Execute command
terraform apply -auto-approve -var 'vm_condition_poweron=false'
- null_resource will be executed every time, but according to if-else statement in command, if you do not need to shutdown vms(vm_condition_poweron=true, by default)- it just echo
do nothing