Reputation: 1
Instead of doing a "virsh undefine " on the host to power-off a VM, is there a way I can do it using terraform?
I tried editing the terraform.tfstate file and trying to do a "terraform plan/apply -replace", but I am hitting some issues, realized that editing tfstate files will not work (and it's not advised to manually edit them)
And trying to modify the workspace tfvars variable and running apply doesn't "overwrite" it, it throws an error saying domain already exists.
Any suggestions would be appreciated, thanks in advance.
Upvotes: 0
Views: 377
Reputation: 119
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:
variable "vm_condition_poweron" {
default = true
}
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]}"
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}"
}
}
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"
}
}
terraform apply -auto-approve -var 'vm_condition_poweron=false'
do nothing
Upvotes: 0