Kvm quickly creates a virtual machine script

Preliminary preparation

First prepare a virtual machine to install and optimize OK, and make the configuration file and disk file into a template

Use differential mirroring and sed to modify the name , uuid , disk path , mac in the configuration file , and then use

Copy the template configuration and virtual machine disk file to /share/kvm/

# mkdir /share/kvm -p
# cp /etc/libvirt/qemu/kvm1.xml /share/kvm/centos7.6.xml
# cp /var/lib/libvirt/images/kvm1.qcow2 /share/kvm/centos7.6.qcow2

2, modify the name in the configuration file , uuid, disk path, mac are vmname, vmuuid, vmdisk, vmmac these 4 names respectively

# vim /share/kvm/centos7.6.xml

<domain type='kvm'>
  <name>vmname</name>											修改为vmname
  <uuid>vmuuid</uuid>											修改为vmuuid
......
......
......
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='vmdisk'/>									修改为vmdisk
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
    </disk>
......
......
......
    <interface type='network'>
      <mac address='vmmac'/>									修改为vmmac
      <source network='default'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
......
......
......

3. Write script (can be modified freely)

# vim /share/kvm/create_kvm.sh

#!/bin/bash

# 使用下面命令产生符合格式的uuid和MAC地址
vmuuid=$(uuidgen)
vmmac="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed -r 's/^(..)(..)(..)(..).*$/\1:\2:\3:\4/')"


read -p "请输入要创建的kvm虚拟机名称:" name
vmname=/etc/libvirt/qemu/$name
vmdisk=/var/lib/libvirt/images/$name.qcow2

# 拷贝模板到对应的路径位置,磁盘文件使用的是差量镜像
cp /share/kvm/centos7.6.xml $vmname.xml
qemu-img create -f qcow2 -b /share/kvm/centos7.6.qcow2 $vmdisk &> /dev/null


# 将上面产生好的变量值使用sed修改配置文件,并define使之生效(sed使用#,因为路径为/,用#替换不用转义)
sed -ri "s#vmname#$name#"   $vmname.xml
sed -ri "s#vmuuid#$vmuuid#" $vmname.xml
sed -ri "s#vmdisk#$vmdisk#" $vmname.xml
sed -ri "s#vmmac#$vmmac#"   $vmname.xml

virsh define $vmname.xml

echo "$name创建完成"
virsh list --all

Test the script, as long as you boot and modify the IP, you can get a new virtual machine

 

Guess you like

Origin blog.csdn.net/weixin_50801368/article/details/112653830