WIP Add KVM host backup recipe

Add a recipe that configures scripts for live backups of VM images via
libvirt and borg.
This commit is contained in:
Râu Cao 2022-10-18 18:45:17 +02:00
parent 6d50a32aca
commit a3844b7ef6
Signed by: raucao
GPG Key ID: 15E65F399D084BA9
3 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,30 @@
#!/bin/bash
# GENERATED BY CHEF
# DO NOT EDIT
set -e
REPOSITORY=$BORG_REPO
echo "Starting backup of VM: $1"
echo "Dumping domain XML to /root/backups/vm_meta/$1.xml"
virsh dumpxml --migratable $1 > /root/backups/vm_meta/$1.xml
virsh snapshot-create-as --domain $1 \
--name hotswap.qcow2 \
--no-metadata \
--atomic \
--quiesce \
--disk-only \
--diskspec vda,snapshot=external
borg create -v --stats \
$REPOSITORY::$1_$(date +%F_%H-%M) \
/var/lib/libvirt/images/$1.qcow2 \
/root/backups/vm_meta
echo "Pivoting base image back to original"
virsh blockcommit $1 vda --pivot --base=/var/lib/libvirt/images/$1.qcow2
echo "Removing snapshot image"
rm /var/lib/libvirt/images/$1.hotswap.qcow2

View File

@ -0,0 +1,40 @@
#
# Cookbook:: kosmos_kvm
# Recipe:: backup
#
apt_package "borgbackup"
borg_credentials = data_bag_item("credentials", "borg")
file "/root/.ssh/borg_rsa" do
content borg_credentials["ssh_key"]
mode '0600'
end
bash "Add borg environment variables for bash" do
code <<-EOF
cat >>/root/.bashrc <<EOL
# GENERATED BY CHEF
export BORG_RSH='ssh -i /root/.ssh/borg_rsa'
export BORG_PASSPHRASE=#{borg_credentials["passphrase"]}
export BORG_REPO='#{borg_credentials["repository"]}'
EOF
not_if "grep -q BORG /root/.bashrc"
end
cookbook_file "/root/backups/backup_vm.sh" do
source "backup_vm.sh"
mode "0750"
end
# Search all guests and filter by presence on current host
vm_domains = search(:node, "role:kvm_guest").map(&:name) \
& `virsh list --name`.strip.chomp.split("\n")
template "/root/backups/backup_all_vms.sh" do
source "backup_all_vms.sh.erb"
mode '0750'
variables vm_domains: vm_domains
end

View File

@ -0,0 +1,11 @@
#!/bin/bash
# GENERATED BY CHEF
# DO NOT EDIT
set -e
echo "Backing up all VMs with kvm_guest chef role..."
for domain in <%= @vm_domains.join(" ") %>
do
/root/backups/backup_vm.sh $domain
done