Deploying a KVM/Libvirt VM through Ansible
2 min readJan 31, 2021
For this article I already have a fedora based server running which I want to deploy a pre-packaged Virtual Machine through Ansible.
First, we’ll look at the task YAML file which will let us deploy the Virtual Machine (roles/vm/tasks/main.yml):
---
- name: Create a directory if it does not exist
file:
path: /opt/vms
state: directory
mode: '0755'
- name: Upload VM Image
unarchive:
src: your-vm-name.zip
dest: /opt/vms- name: Install Cockpit
yum: name=cockpit state=present- name: Install Libvirt
yum: name=libvirt state=present- name: Install KVM
yum: name=qemu-kvm state=present- name: Install QEMU
yum: name=qemu state=present- name: Start service libvirt
service:
name: libvirtd
state: started- name: Install Cockpit Machines Extension
yum: name=cockpit-machines state=present- name: Define VM
community.libvirt.virt:
command: define
xml: "{{ lookup('file', 'your-vm.xml') }}"- name: Start VM
community.libvirt.virt:
name: your-vm
state: running- name: set autostart for a VM
community.libvirt.virt:
name: your-vm
autostart: yes
This task will execute the following steps for us:
- First, it will create a folder (if it does not exist) at /opt/vms. This is the location I typically have my Virtual Machine stored.
- Then it will upload the zip file containing the qcow2 file. This zip file is located in roles/vm/files/ directory.
- Next ansible will make sure that all dependencies required to run the virtual machine are present. I like to use Cockpit to manage my VMs, therefore I also install
- As a next step, a previously created XML, describing the Virtual Machine, is imported. You can create this file yourself through virt-manager locally, then executing virsh dumpxml to retrieve the XML.
- As a final step, we configure this VM to be automatically started upon system startup.
In your site.yml you’ll typically need to ensure that “become: yes” is set on the vm role.
---
- hosts: vm
remote_user: <your-user>
become: yes
roles:
- vm
Next, you can assign this role to a host through an inventory file:
[vm]
<ip-or-hostname>