安装好Centos虚机系统,进行标准化配置,最后安装cloud-init,如下:
yum -y install qemu-guest-agent
yum -y install cloud-init
systemctl enable cloud-init-local.service
systemctl start cloud-init-local.service
systemctl enable cloud-init.service
systemctl start cloud-init.service
systemctl enable cloud-config.service
systemctl start cloud-config.service
systemctl enable cloud-final.service
systemctl start cloud-final.service
cloud-init init --local #检查是否可用
配置完成后关机,删除硬件网卡,添加 Cloud-Init 硬件,然后转换为模板
qm set 1003 --ide2 local-lvm:cloudinit
通过模板克隆新的虚机,自动配置IP,脚本如下:
#!/bin/bash
#Function:Clone 1 vm from template
host='10.10.20.11'
vmname='vmtest02'
cpu_cores=8
memory_size=16384
ip='10.10.26.21'
vlanid=26
description='description'
#get vm max id
pve_id_max=`qm list |awk '{print $1}' |tail -n 1`
pve_vm_id=`expr $pve_id_max + 1`
#get cpu cores every cpu socket
cpu_cores_1=`expr $cpu_cores / 2`
storage=`echo $host |awk -F . '{print "dir-"$4}'`
ip_netmask="$ip/24"
gateway=`echo $ip |awk -F . '{print $1"."$2"."$3".254"}'`
vm_hostname="$vmname-$ip"
#clone vm from template(100)
qm clone 100 $pve_vm_id --name $vmname --full --format qcow2 --storage $storage
#configure vm cpu cors and memory size
if [ $cpu_cores -ne 4 -a $memory_size -ne 8192 ];then
qm set $pve_vm_id --memory $memory_size --sockets 2 --cores $cpu_cores_1
fi
#configure vm description
if [ $description ];then
qm set $pve_vm_id --description=$description
fi
qm set $pve_vm_id --onboot #开机自启动
qm set $pve_vm_id --agent #启用vm agent
qm set $pve_vm_id --localtime 1 #linux虚机默认为0,会使用utc时间,需要配置为1使用本地时间
qm set $pve_vm_id -net0 e1000,bridge=vmbr1,firewall=1,tag=$vlanid
qm set $pve_vm_id --ipconfig0 ip=$ip_netmask,gw=$gateway
#qm set $pve_vm_id --cipassword:123456 --ciuser:root #为root设置密码
echo 'Start and init vm for about 5 minutes...'
#删除clould-init硬件,修改虚机名称
qm start $pve_vm_id
sleep 300
qm stop $pve_vm_id
sleep 2
qm set $pve_vm_id --delete ide2
sleep 2
qm set $pve_vm_id --name $vm_hostname
qm start $pve_vm_id