In this video I configure a dynamic inventory in Ansible for quem kvm guest using community.libvirt
Some notes on this plugin are.
- currently DOES NOT work with selinux set to enforcing in the VM.
- Requires the qemu-agent installed in the VM.
- Requires access to the qemu-ga commands guest-exec, guest-exec-status, guest-file-close, guest-file-open, guest-file-read, guest-file-write.
This works with remote host and linux containers but in the video I did this all local.
First I installed the collection.
ansible-galaxy collection install community.libvirt
Created a dynamic inventory
$ cat kvm.yml
# Connect to qemu
plugin: community.libvirt.libvirt
uri: 'qemu:///system'
Note the uri would change for lxc or remote connections.
After the inventory set up test it
ansible-inventory --inventory kvm.yml --list
You should see the info about your guest. If you get red or an error verify that the guest agent is running and that it has access to the guest-exec and guest-file commands.
A good way to test the guest agent is with a guest execute of ls
virsh qemu-agent-command “Name of your Guest VM” '{"execute": "guest-exec", "arguments": { "path": "/usr/bin/ls", "arg": [ "/" ], "capture-output": true }}'
If you have issues take a look at my previous video where I provisioned the guest https://thenathan.net/2022/09/29/virt-builder/.
Once your inventory is working you can connect with the console.
ansible-console --inventory kvm.yml -l “Name of your Guest VM”
I used -l to limit because I only had the one host running.
Now we are in the console and can run some commands to test
ls
cat /etc/redhat-release
whoami
exit
This is the very simple playbook I used to test playbooks running against the inventory. t
$ cat dnf_update_reboot.yml
---
- hosts: alma8
gather_facts: false
become: true
any_errors_fatal: yes
tasks:
- name: DNF update the system
dnf:
name: "*"
state: latest
- name: Install the latest version of yum-utils
dnf:
name: yum-utils
state: latest
- name: Reboot required
command: "/usr/bin/needs-restarting -r"
register: reboot_required
ignore_errors: True
changed_when: False
failed_when: reboot_required.rc == 2
- name: Rebooting
reboot:
post_reboot_delay: 60
throttle: 1
when: reboot_required.rc == 1 and ansible_facts ['virtualization_role'] != 'host'boot_required.rc == 1 and ansible_facts ['virtualization_role'] != 'host'
You can run the playbook with the ansible-playbook command
ansible-playbook -i kvm.yml dnf_update_reboot.yml
ansible-console –inventory kvm.yml -l “Name of your Guest VM”