Skip to content

Instantly share code, notes, and snippets.

@bdmorin
Created July 18, 2024 09:58
Show Gist options
  • Save bdmorin/2ebc4296208898edd85bcb7ac08446c9 to your computer and use it in GitHub Desktop.
Save bdmorin/2ebc4296208898edd85bcb7ac08446c9 to your computer and use it in GitHub Desktop.
ansible shutdown vms
---
- name: Schedule VM shutdown and server reboot
hosts: kvm_servers
become: yes
vars:
shutdown_time: "23:00"
tasks:
- name: Create a cron job to shutdown VMs and reboot server
cron:
name: "Shutdown VMs and reboot server"
minute: "{{ shutdown_time.split(':')[1] }}"
hour: "{{ shutdown_time.split(':')[0] }}"
job: "/usr/bin/ansible-playbook /path/to/shutdown_vms_and_reboot.yml"
- name: Shutdown VMs and reboot server
hosts: kvm_servers
become: yes
tasks:
- name: Gather list of running VMs
command: virsh list --name
register: running_vms
- name: Shutdown running VMs
command: "virsh shutdown {{ item }}"
loop: "{{ running_vms.stdout_lines }}"
when: item != ""
- name: Wait for VMs to shutdown
command: "virsh list --name"
register: vms_after_shutdown
until: vms_after_shutdown.stdout_lines == []
retries: 10
delay: 30
- name: Reboot the server
reboot:
reboot_timeout: 3600
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment