Skip to content

Instantly share code, notes, and snippets.

@Enelar
Last active August 13, 2023 02:14
Show Gist options
  • Save Enelar/c3901592172a0a8a4286c21f117c8029 to your computer and use it in GitHub Desktop.
Save Enelar/c3901592172a0a8a4286c21f117c8029 to your computer and use it in GitHub Desktop.
Add rbd pool to kvm
#!/bin/bash
# ChatGPT from https://blog.modest-destiny.com/posts/kvm-libvirt-add-ceph-rbd-pool/
# Allows adding multiple pools and use shared secret between them
# Define variables
VIRT_SCRT_PATH="/tmp/libvirt-secret.xml"
VIRT_POOL_PATH="/tmp/libvirt-rbd-pool.xml"
# Get script arguments
POOL_NAME=$1
CEPH_HOST=$2
CEPH_USER="libvirt"
# Check if a secret for the client user already exists
SECRET_EXISTS=$(virsh secret-list | grep client.libvirt)
if [ -z "$SECRET_EXISTS" ]; then
echo "No secret exists for the client.libvirt user. Creating a new one."
VIRT_SCRT_UUID=$(uuidgen)
# Create and define the secret
cat > "${VIRT_SCRT_PATH}" <<EOF
<secret ephemeral='no' private='no'>
<uuid>${VIRT_SCRT_UUID}</uuid>
<usage type='ceph'>
<name>client.${CEPH_USER} secret</name>
</usage>
</secret>
EOF
virsh secret-define --file "${VIRT_SCRT_PATH}"
rm -f "${VIRT_SCRT_PATH}"
virsh secret-set-value --secret "${VIRT_SCRT_UUID}" --base64 "$(ceph auth get-key client.${CEPH_USER})"
else
VIRT_SCRT_UUID=$(virsh secret-list | grep client.libvirt | awk '{print $1;}')
echo "A secret already exists for this user with the following UUID: ${VIRT_SCRT_UUID}"
fi
# Create and define the pool
cat > "${VIRT_POOL_PATH}" <<EOF
<pool type="rbd">
<name>${POOL_NAME}</name>
<source>
<name>${POOL_NAME}</name>
<host name='${CEPH_HOST}' port='6789' />
<auth username='${CEPH_USER}' type='ceph'>
<secret uuid='${VIRT_SCRT_UUID}'/>
</auth>
</source>
</pool>
EOF
virsh pool-define "${VIRT_POOL_PATH}"
rm -f "${VIRT_POOL_PATH}"
virsh pool-autostart "${POOL_NAME}"
virsh pool-start "${POOL_NAME}"
#!/bin/bash
# Cleans all resources created by previous script
POOL_NAME=$1
CEPH_USER="libvirt"
# Check current pool lists
POOL_LIST=$(virsh pool-list --all | grep -o $POOL_NAME | uniq)
# Destroy and undefine the pool
virsh pool-destroy "${POOL_NAME}"
virsh pool-undefine "${POOL_NAME}"
# Delete the secret if no more pools
if [[ -z "$POOL_LIST" ]]
then
SECRET_UUID=$(virsh secret-list | grep "client.${CEPH_USER} secret" | awk '{print $1}')
virsh secret-undefine "${SECRET_UUID}"
echo "Secret ${SECRET_UUID} is removed."
else
echo "Seems there are still some pools associated with the secret. Secret not removed."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment