From 7a8e0877316cbc005307c00b2c783b0e2574d328 Mon Sep 17 00:00:00 2001
From: Mark Goddard <mark@stackhpc.com>
Date: Mon, 7 Aug 2017 11:57:21 +0000
Subject: [PATCH] Change ownership of libvirt volume to qemu:qemu after
 creation

This allows libvirt, which runs as the qemu user, to access the volume.
---
 ansible/roles/libvirt-vm/files/virt_volume.sh | 22 +++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/ansible/roles/libvirt-vm/files/virt_volume.sh b/ansible/roles/libvirt-vm/files/virt_volume.sh
index 006babcf8..f425f6a9e 100644
--- a/ansible/roles/libvirt-vm/files/virt_volume.sh
+++ b/ansible/roles/libvirt-vm/files/virt_volume.sh
@@ -49,6 +49,27 @@ if [[ $result -ne 0 ]]; then
     exit $result
 fi
 
+# Determine the path to the volume file.
+output=$(virsh vol-key --pool $POOL --vol $NAME 2>&1)
+result=$?
+if [[ $result -ne 0 ]]; then
+    echo "Failed to get volume file path"
+    echo "$output"
+    virsh vol-delete --pool $POOL --vol $NAME
+    exit $result
+fi
+
+# Change the ownership of the volume to qemu. Without doing this libvirt cannot
+# access the volume.
+output=$(chown qemu:qemu $output 2>1)
+result=$?
+if [[ $result -ne 0 ]]; then
+    echo "Failed to change ownership of the volume to qemu"
+    echo "$output"
+    virsh vol-delete --pool $POOL --vol $NAME
+    exit $result
+fi
+
 if [[ -n $IMAGE ]]; then
     # Upload an image to the volume.
     output=$(virsh vol-upload --pool $POOL --vol $NAME --file $IMAGE 2>&1)
@@ -66,6 +87,7 @@ if [[ -n $IMAGE ]]; then
     if [[ $result -ne 0 ]]; then
         echo "Failed to resize volume $VOLUME to $CAPACITY"
         echo "$output"
+        virsh vol-delete --pool $POOL --vol $NAME
         exit $result
     fi
 fi