KVM 一鍵批量建立虛擬機器 自動設定IP

自由早晚亂餘生發表於2020-05-01

一、原理

  1. 需要先建立基礎映象,後續的映象都是基於該映象建立的差量映象。基礎映象不允許修改(需要注意)。
  2. 基礎映象需要設定要一些基本內容。
  3. 通過 virt-edit 實現的設定ip.
  4. ip 資訊統一用 <title> 來進行標記。 使用virsh list --title進行檢視 機器和IP

完成的功能:
輸入機器名稱和ip,就能建立我們想要的虛擬機器了。ip會自動幫我們設定好。

解決的問題:

  1. 之前建立機器後需要手動去設定IP. virt-edit 進行編輯網路檔案。
  2. 建立完機器,我們不知道機器對應的哪個IP. 使用 <title> 來進行標記。 使用virsh list --title進行檢視 機器和IP對應關係

二、基礎映象

2.1、建立基礎映象

  • 記憶體為8G 和2核
  • 磁碟為50G
  • vnc 埠使用隨機
  • 網路設定為橋接
  • 機器設定為自動啟動
virt-install --name base-image --virt-type kvm --memory 8096 --vcpus 2 --cdrom=/home/kvm/iso/CentOS-7-x86_64-Minimal-1908.iso --disk /home/kvm/data/base-image.qcow2,size=50,format=qcow2  --graphics vnc,listen=0.0.0.0  --network network=net-br --autostart  

2.2、 完善基礎映象

  1. 增加 console 登陸

    grubby --update-kernel=ALL --args="console=ttyS0,115200n8"
    
  2. vnc 埠設定隨機

  3. 使用橋接網路

  4. 設定網路配置

    BOOTPROTO=static  
    ONBOOT=yes
    IPADDR=192.168.1.12
    NETMASK=255.255.255.0
    GATEWAY=192.168.1.1
    DNS1=192.168.1.1
    # 註釋uuid
    

2.3、基礎映象設定許可權

由於使用的是差量映象的模式,所以基礎映象不允許修改。

chattr +i   /opt/kvm/data/base-image.qcow2

3.4 設定 title

編輯基礎映象的 xml 檔案,增加 title。

 <title>192.168.1.156</title>

3.5、基礎映象XML

<!--
WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
OVERWRITTEN AND LOST. Changes to this xml configuration should be made using:
  virsh edit base-image
or other application using the libvirt API.
-->

<domain type='kvm'>
  <name>base-image</name>
  <uuid>12348899-e829-4217-a0ff-f30eee4d2b31</uuid>
  <title>192.168.1.199</title>
  <memory unit='KiB'>16777216</memory>
  <currentMemory unit='KiB'>8388608</currentMemory>
  <vcpu placement='static' current='2'>4</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
  </features>
  <cpu mode='custom' match='exact' check='partial'>
    <model fallback='allow'>Broadwell-IBRS</model>
    <feature policy='require' name='spec-ctrl'/>
  </cpu>
  <clock offset='utc'>
    <timer name='rtc' tickpolicy='catchup'/>
    <timer name='pit' tickpolicy='delay'/>
    <timer name='hpet' present='no'/>
  </clock>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <pm>
    <suspend-to-mem enabled='no'/>
    <suspend-to-disk enabled='no'/>
  </pm>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/opt/kvm/data/base-image.qcow2'/>
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </disk>
    <disk type='file' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <target dev='hda' bus='ide'/>
      <readonly/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0' model='ich9-ehci1'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x7'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci1'>
      <master startport='0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0' multifunction='on'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci2'>
      <master startport='2'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x1'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci3'>
      <master startport='4'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <controller type='virtio-serial' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </controller>
    <interface type='network'>
      <mac address='52:54:00:28:99:22'/>
      <source network='net-br'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target type='isa-serial' port='0'>
        <model name='isa-serial'/>
      </target>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <channel type='unix'>
      <target type='virtio' name='org.qemu.guest_agent.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='1'/>
    </channel>
    <input type='tablet' bus='usb'>
      <address type='usb' bus='0' port='1'/>
    </input>
    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>
    <graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0' keymap='en-us'>
      <listen type='address' address='0.0.0.0'/>
    </graphics>
    <video>
      <model type='cirrus' vram='16384' heads='1' primary='yes'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
    </memballoon>
    <rng model='virtio'>
      <backend model='random'>/dev/urandom</backend>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x08' function='0x0'/>
    </rng>
  </devices>
</domain>

三、批量建立機器指令碼

因為需要使用 virt-edit,所以需要安裝libguestfs-tools
yum install -y libguestfs-tools

#!/bin/bash
#######################################################
# $Name:        create_kvm_machine.sh
# $Version:     v1.0
# $Function:    create kvm machine
# $Author:      dongjiaxiao
# $Create Date: 2020-04-12
# $Description: shell
######################################################
#set -x
# 檢查基礎映象和xml是否存在並生成uuid,mac 資訊
function check(){
	if [ ! -f "${xmls_dir}${base_xml}" ]&&[ ! -f "${images_dir}${base_img}" ] # 判斷基礎xml和基礎映象是否存在
	then
		echo "基礎映象或者基礎映象xml不存在"
		exit 1
	else
   		vir_uuid=`uuidgen`
		vir_mac="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum |sed -r 's/^(..)(..)(..)(..).*$/\1:\2:\3:\4/')"
		vir_name=$machine_name        
	fi 
	
}
#建立磁碟
function create_disk(){
	chattr -i  ${images_dir}$base_img
	qemu-img create -f qcow2 -b ${images_dir}$base_img ${images_dir}${vir_name}.qcow2 ${vir_disk}G  &>/dev/null
}
#新增磁碟
function attach_disk(){
	qemu-img create -f qcow2  ${images_dir}${vir_name}-2.qcow2  ${vir_attach_disk}G  >/dev/null
	virsh attach-disk ${vir_name} ${images_dir}${vir_name}-2.qcow2 vdb --cache writeback --subdriver qcow2 --persistent >/dev/null
	
}

#配置xml ,替換記憶體cpu 等資訊並匯入
function conf_xml(){
	cp  ${xmls_dir}${base_xml}  /tmp/${vir_name}.xml
	sed -i "s#<memory unit='KiB'>.*</memory>#<memory unit='KiB'>${vir_mem}</memory>#"  /tmp/${vir_name}.xml 
	sed -i "s#<currentMemory unit='KiB'>.*</currentMemory>#<currentMemory unit='KiB'>${vir_mem}</currentMemory>#"   /tmp/${vir_name}.xml 
	sed -i "s#<vcpu placement='static'>.*</vcpu>#<vcpu placement='static'>${vir_cpu}</vcpu>#" /tmp/${vir_name}.xml
	sed -i "s/<name>.*<\/name>/<name>${vir_name}<\/name>/" /tmp/${vir_name}.xml
	sed -i "s/<uuid>.*<\/uuid>/<uuid>${vir_uuid}<\/uuid>/" /tmp/${vir_name}.xml
	sed -i "s/<title>.*<\/title>/<title>${vir_ip}<\/title>/" /tmp/${vir_name}.xml
	sed -i "s#<source file=.*/>#<source file='${images_dir}${vir_name}.qcow2'/>#" /tmp/${vir_name}.xml
	sed -i "s/<mac address=.*\/>/<mac address='$vir_mac' \/>/" /tmp/${vir_name}.xml
	virsh define /tmp/${vir_name}.xml >/dev/null
	virt-edit -d ${vir_name}  /etc/sysconfig/network-scripts/ifcfg-eth0  -e "s#IPADDR=".*"#IPADDR="${vir_ip}"#"  # 替換ip
}

#啟動並設定開機自啟
function start_vir(){
	virsh start ${vir_name} >/dev/null
	virsh autostart ${vir_name} >/dev/null
	chattr +i  ${images_dir}$base_img
}
#記錄建立日誌
function create_vir_log(){
	echo "$(date +%F_%T)  vir_name: ${vir_name} vir_ip: ${vir_ip} !"   >>$vir_log_file
	echo "$(date +%F_%T)  vir_name: ${vir_name} vir_ip: ${vir_ip} 建立成功!" 
}

main(){
    images_dir="/home/kvm/data/" # 映象儲存的位置
    base_img="base-image.qcow2"  # 基礎映象的名稱
    xmls_dir="/etc/libvirt/qemu/"  # xml 的位置
    base_xml="base-image.xml"   # 基礎xml的名稱 
    vir_log_file="/tmp/kvm_create_log.txt" # 建立日誌檔案
    vir_disk=50 # 磁碟預設為50G  
    vir_cpu=2 # cpu預設為2核
    vir_mem=8388608 # 記憶體預設為8G
    echo -e "伺服器配置選項:\n 1: 2核8G 50G(測試) \n 2: 1核8G 50G(開發) \n 3: 2核8G 100G(資料庫) \n 4: 4核20G 200G" 
    read  -t 30 -p  "輸入你選擇的配置的編號(1-4):" number
    read  -t 90 -p "輸入想要建立的IP(192.168.1.1):"  vir_ip
    read  -t 120 -p "輸入想要建立的機器名稱(haha-biz-1234567-test):"  machine_name
    if [ -z "$vir_ip" ] || [  -z "$machine_name" ] # 判斷是否輸入ip和機器名稱
    then
       echo "請輸入ip和機器名稱"
       exit -1
    fi
    case "$number" in
        [1] )
            check
            create_disk
            conf_xml
            start_vir
            create_vir_log
        ;;
        [2] )
            vir_cpu=1  # 設定為1核
            check
            create_disk
            conf_xml
            start_vir
            create_vir_log
        ;;
        [3] )
            vir_disk=100 #設定為磁碟100G盤
            check
            create_disk
            conf_xml
            start_vir
            create_vir_log
        ;;
        [4] )
            base_img="dc-base-image.qcow2"
            vir_cpu=4  # 設定為4核
            vir_mem=20971520 #設定記憶體為20G
            vir_disk=20 #設定為磁碟200G盤
            vir_attach_disk=200 # 設定附加盤的大小
            check
            create_disk
            conf_xml
            start_vir
            attach_disk
            create_vir_log
        ;;
        *) echo "輸入編號(1-4)";;
    esac
}
main

四、掛載磁碟多種方式

擴充套件物件為: 虛擬機器

4.1 擴容現有的磁碟

  • 這種方式只能增加不能縮小
  • 需要先把虛擬機器關閉。(注意)
  • 宿主機操作

    [root@djx-kvm-123456-test opt]# virsh  shutdown   djx-mysql-djxmysq-test
    [root@djx-kvm-123456-test opt]# qemu-img info /home/kvm/data/djx-mysql-djxmysq-test.qcow2
    image: /home/kvm/data/djx-mysql-djxmysq-test.qcow2
    file format: qcow2
    virtual size: 100G (107374182400 bytes)
    disk size: 131M
    cluster_size: 65536
    backing file: /home/kvm/data/base-image.qcow2
    Format specific information:
        compat: 1.1
        lazy refcounts: false
    [root@djx-kvm-af3r34t-test opt]# qemu-img resize /home/kvm/data/djx-mysql-djxmysq-test.qcow2 +3G
    Image resized.
    [root@djx-kvm-af3r34t-test opt]# qemu-img info /home/kvm/data/djx-mysql-djxmysq-test.qcow2
    image: /home/kvm/data/djx-mysql-djxmysq-test.qcow2
    file format: qcow2
    virtual size: 103G (110595407872 bytes)
    disk size: 254M
    cluster_size: 65536
    backing file: /home/kvm/data/base-image.qcow2
    Format specific information:
        compat: 1.1
        lazy refcounts: false
    
    
  • 虛擬機器操作

虛擬機器可以進行兩種型別的操作:(以下兩步是衝突的,只能2選1)
1、是使用新增空間擴容現有的磁碟
2、是使用新增空間建立新的分割槽

  • 使用新增空間擴容現有的磁碟

    # 核心版本大於3.6.0
    
    # 安裝 growpart或者xfsprogs擴容格式化工具
    yum install cloud-utils-growpart
    yum install xfsprogs
    # 執行fdisk -l命令檢視現有云盤大小
    [root@localhost ~]# df -h 
    Filesystem      Size  Used Avail Use% Mounted on
    devtmpfs        3.9G     0  3.9G   0% /dev
    tmpfs           3.9G     0  3.9G   0% /dev/shm
    tmpfs           3.9G  8.5M  3.9G   1% /run
    tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup
    /dev/vda2        50G  1.2G   49G   3% /
    /dev/vda1       497M  134M  363M  27% /boot
    tmpfs           783M     0  783M   0% /run/user/0
    [root@localhost ~]# fdisk  -l 
    
    Disk /dev/vda: 107.4 GB, 107374182400 bytes, 209715200 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk label type: dos
    Disk identifier: 0x000a6596
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/vda1   *        2048     1026047      512000   83  Linux
    /dev/vda2         1026048   104857599    51915776   83  Linux
    # 檢視分割槽的檔案系統型別
    [root@localhost ~]# blkid  /dev/vda2 
    /dev/vda2: UUID="be6f97e3-13c3-46ea-9694-78a575272bb8" TYPE="xfs" 
    # 呼叫growpart為需要擴容的雲盤和對應的第幾個分割槽擴容
    [root@localhost ~]# growpart   /dev/vda 2
    CHANGED: partition=2 start=1026048 old: size=103831552 end=104857600 new: size=208689119 end=209715167
    # 執行xfs_growfs <PartitionName>命令呼叫xfs_growfs擴容檔案系統。 
    #  xfs 檔案系統使用xfs_growfs   ,ext4 檔案系統使用 resize2fs 
    [root@localhost ~]# xfs_growfs  /dev/vda2
    meta-data=/dev/vda2              isize=512    agcount=4, agsize=3244736 blks
             =                       sectsz=512   attr=2, projid32bit=1
             =                       crc=1        finobt=0 spinodes=0
    data     =                       bsize=4096   blocks=12978944, imaxpct=25
             =                       sunit=0      swidth=0 blks
    naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
    log      =internal               bsize=4096   blocks=6337, version=2
             =                       sectsz=512   sunit=0 blks, lazy-count=1
    realtime =none                   extsz=4096   blocks=0, rtextents=0
    data blocks changed from 12978944 to 26086139
    
    
  • 使用新增空間建立新的分割槽(與上一步衝突的)

    [root@localhost ~]# fdisk  /dev/vda 
    Welcome to fdisk (util-linux 2.23.2).
    
    Changes will remain in memory only, until you decide to write them.
    Be careful before using the write command.
    
    
    Command (m for help): m
    Command action
       a   toggle a bootable flag
       b   edit bsd disklabel
       c   toggle the dos compatibility flag
       d   delete a partition
       g   create a new empty GPT partition table
       G   create an IRIX (SGI) partition table
       l   list known partition types
       m   print this menu
       n   add a new partition
       o   create a new empty DOS partition table
       p   print the partition table
       q   quit without saving changes
       s   create a new empty Sun disklabel
       t   change a partition's system id
       u   change display/entry units
       v   verify the partition table
       w   write table to disk and exit
       x   extra functionality (experts only)
    
    Command (m for help): n
    Partition type:
       p   primary (2 primary, 0 extended, 2 free)
       e   extended
    Select (default p): p
    Partition number (3,4, default 3):  
    First sector (104857600-209715199, default 104857600): 
    Using default value 104857600
    Last sector, +sectors or +size{K,M,G} (104857600-209715199, default 209715199): 
    Using default value 209715199
    Partition 3 of type Linux and of size 50 GiB is set
    
    Command (m for help): w
    The partition table has been altered!
    
    Calling ioctl() to re-read partition table.
    
    WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
    The kernel still uses the old table. The new table will be used at
    the next reboot or after you run partprobe(8) or kpartx(8)
    Syncing disks.
    [root@localhost ~]# fdisk  -l
    
    Disk /dev/vda: 107.4 GB, 107374182400 bytes, 209715200 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk label type: dos
    Disk identifier: 0x000a6596
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/vda1   *        2048     1026047      512000   83  Linux
    /dev/vda2         1026048   104857599    51915776   83  Linux
    /dev/vda3       104857600   209715199    52428800   83  Linux
    # 然後需要重啟機器。不然直接掛載的話是掛載不了的。
    # 格式化磁碟
    [root@localhost ~]mkfs.xfs  /dev/vda3 
    [root@localhost ~]# mount  /dev/vda3  /home
    # 如果沒有重啟 ,報錯 mount: special device /dev/vda3 does not exist
    
    # 還需要設定開動掛載
    

4.2 新增新的磁碟

  • 宿主機操作

    [root@k5-m2 ~]# qemu-img create -f qcow2  /home/kvm/data/djx-biz-djx1234-dev-2.qcow2  10G
    Formatting '/home/kvm/data/djx-biz-djx1234-dev-2.qcow2', fmt=qcow2 size=10737418240 encryption=off cluster_size=65536 lazy_refcounts=off
    [root@k5-m2 ~]# virsh attach-disk djx-biz-djx1234-dev  /home/kvm/data/djx-biz-djx1234-dev-2.qcow2 vdb --cache writeback --subdriver qcow2 --persistent
    Disk attached successfully
    
    [root@djx-kvm-af3r34t-test data]# virsh domblklist  djx-biz-djx1234-dev
    Target     Source
    ------------------------------------------------
    vda        /home/kvm/data/djx-biz-djx1234-dev.qcow2
    vdb        /home/kvm/data/djx-biz-djx1234-dev-2.qcow2
    hda        -
    
    
  • 虛擬機器操作

    [root@localhost ~]# fdisk  -l 
    
    Disk /dev/vda: 85.9 GB, 85899345920 bytes, 167772160 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk label type: dos
    Disk identifier: 0x000a6596
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/vda1   *        2048     1026047      512000   83  Linux
    /dev/vda2         1026048   104857599    51915776   83  Linux
    /dev/vda3       104857600   167772126    31457263+  83  Linux
    
    Disk /dev/vdb: 10.7 GB, 10737418240 bytes, 20971520 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    # 我們可以在系統盤這邊看到我們新增加的磁碟,然後我們可以對該磁碟進行初始化和分割槽,並掛載使用了,注意在掛載的時候需要注意設定開機自動掛載。
    具體操作見 7.1 虛擬機器操作-使用新增空間建立新的分割槽
    

五、常用操作命令

  • 檢視虛擬機器對應的ip

    virsh list --title
    
  • 登入虛擬機器

    • 通過 console

      virsh console djx-biz-qawsed4-test
      
    • 通過 ssh

    • 通過 vnc

      vnc 埠為隨機。通過查詢對應的程式來獲取。

  • virsh list [--all] #檢視所有KVM虛擬機器

  • virsh dominfo name # 檢視虛擬機器 CPU/記憶體的使用率

  • virsh start name #啟動KVM虛擬機器

  • virsh shutdown name #正常關閉KVM虛擬機器、基本是關不掉的

  • virsh autostart name # 設定開機自啟

  • virsh autostart –disable name # 關閉開機自啟

  • virsh destroy name #強制關閉KVM虛擬機器(類似於直接斷電)

  • virsh suspend name #掛起KVM虛擬機器

  • virsh resume name #恢復掛起的KVM虛擬機器

  • virsh dumpxml name #檢視KVM虛擬機器配置檔案

  • virsh edit name #編輯KVM虛擬機器的xml配置檔案

  • virsh undefine name #徹底刪除KVM虛擬機器,不可逆,如果想找回來,需要備份/etc/libvirt/qemu的xml檔案

  • virsh snapshot-create name #建立快照

  • virsh snapshot-delete name --current/--snapshotname #刪除快照

  • virsh snapshot-dumpxml name #匯出XML

  • virsh snapshot-list name #檢視快照

相關文章