0

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.

Myra Lii
  • 1
  • 1
  • try to set false in the "running" variable on your libvirt_domain resource. See the doc for reference: https://registry.terraform.io/providers/dmacvicar/libvirt/latest/docs/resources/domain#running – Felipe Bonfante Aug 16 '22 at 11:27
  • @FelipeBonfante manually editing the tfstate file is not recommended is what I saw. But anyways, I set it to false, and tried to do a apply -replace and refresh, it didn't work :( – Myra Lii Sep 07 '22 at 03:55

1 Answers1

0

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:

  1. add variable
variable "vm_condition_poweron" {
  default = true
}

  1. 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]}"

  1. 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"

  }
}

  1. 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
krasnosvar
  • 101
  • 4