Myra Lii
Myra Lii

Reputation: 1

Is there any "terraform way" to shutdown a domain?

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

Answers (1)

krasnosvar
krasnosvar

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:

  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

Upvotes: 0

Related Questions