1、制作模板
将正常安装好的虚拟机配置文件进行复制 并修改其中的参数为以下
cp /etc/libvirt/qemu/centos7.xml centos7-mod.xml
修改参数
9 <name>vm-name</name>
10 <uuid>vm-uuid</uuid>
11 <memory unit='KiB'>vm-mem</memory>
12 <currentMemory unit='KiB'>vm-mem</currentMemory>
41 <disk type='file' device='disk'>
42 <driver name='qemu' type='qcow2'/>
43 <source file='vm-disk-path'/> #修改行
44 <target dev='vda' bus='virtio'/>
45 <address type='pci' domain='0x0000' bus='0x00' slot='0x07' fun ction='0x0'/>
46 </disk>
75 <interface type='network'>
76 <mac address='52:54:00:vm-mac'/> #修改行
77 <source network='default'/>
78 <model type='virtio'/>
79 <address type='pci' domain='0x0000' bus='0x00' slot='0x03' fun ction='0x0'/>
80 </interface>
制作虚拟机硬盘模板
cp /var/lib/libvirt/images/centos7.qcow2 centos7-mod.qcow2
2、创建一个parameter.sh文件用来存储修改模板的参数
read -p "输入vm-name :" name
read -p "输入vm-mem :" mem
vm_name=$name
vm_uuid=`uuidgen`
vm_mem=$mem
vm_disk_path=/home/$name.qcow2
vm_mac=`openssl rand -hex 3 | sed -r 's/..\B/&:/g'`
3、创建虚拟机脚本
#导入储存参数的脚本
source ./parameter.sh
#传递参数
fun_sed(){
sed -r -e s%vm-name%$vm_name% -e s%vm-uuid%$vm_uuid% -e s%vm-mem%$vm_mem% -e s%vm-disk-path%$vm_disk_path% -e s%vm-mac%$vm_mac% ./centos7-mod.xml >> $vm_name.xml
}
#创建虚拟磁盘
fun_disk(){
cp ./centos7-mod.qcow2 /home/$vm_name.qcow2
}
#定义虚拟机并启动
fun_start(){
virsh define $vm_name.xml
virsh start $vm_name
}
#执行函数
fun_sed
fun_disk
#判断本机是否有virsh
yum -y install libvirt-client &>/dev/null
if [ $? != 0 ];then
yum -y install libvirt-client
fi
fun_start