如何利用模板主机快速克隆虚拟机

2019-04-14 17:39发布

一 准备模板主机和XML文件 /var/lib/libvirt/images/下
.ce7_template.img .centos7.xml
二 编写克隆脚本clone-centos7 /var/lib/libvirt/images/bin/下 #!/bin/bash #65 -> user input nothing #66 -> user input is not a number #67 -> user input out of range #68 -> vm disk image exists IMG_DIR=/var/lib/libvirt/images //定义变量IMG_DIR--虚拟机目录 BASEVM=ce7_template //定义变量BASEVM--虚拟主机模板 read -p "Enter VM number: " VMNUM if [ $VMNUM -le 9 ];then VMNUM=0$VMNUM //编号小于9,前面加0,保持两位 fi if [ -z "${VMNUM}" ]; then echo "You must input a number." //输入为空值时的输出结果 exit 65 elif [ $(echo ${VMNUM}*1 | bc) = 0 ]; then echo "You must input a number." //输入为0时的输出结果 exit 66 elif [ ${VMNUM} -lt 1 -o ${VMNUM} -gt 99 ]; then echo "Input out of range" //输入超过99时的输出结果 exit 67 fi NEWVM=ce7_node${VMNUM} //定义变量—-新虚拟机名 if [ -e $IMG_DIR/${NEWVM}.img ]; then //镜像文件已存在 echo "File exists." exit 68 fi echo -en "Creating Virtual Machine disk image...... " cd /var/lib/libvirt/images qemu-img create -f qcow2 -b $IMG_DIR/.${BASEVM}.img $IMG_DIR/${NEWVM}.img &> /dev/null //镜像克隆 echo -e "e[32;1m[OK]e[0m" cat /var/lib/libvirt/images/.centos7.xml > /tmp/myvm.xml sed -i "/${BASEVM}/s/${BASEVM}/${NEWVM}/" /tmp/myvm.xml /tmp/myvm.xml //修改XML文件 sed -i "/${BASEVM}.img/s/${BASEVM}/${NEWVM}/" /tmp/myvm.xml echo -en "Defining new virtual machine...... " virsh define /tmp/myvm.xml &> /dev/null //重新定义生成新虚拟机 echo -e "e[32;1m[OK]e[0m" 三 创建链接文件
ln -s /var/lib/libvirt/images/bin/clone-centos7 /usr/local/bin