定义kickstart文件
install
keyboard 'us'
rootpw --iscrypted $6$dQz7gaBT$IjteQ2XRZmBJD1usRqFv4yaD1Z2UbO2XBCJ8fndZlertVu2DUgsD7K9QDt7k2M5U3usWEc6HN8W0WpowiPo28/
lang en_US
auth --useshadow --passalgo=sha512
text
skipx
selinux --disabled
firewall --disabled
network --bootproto=dhcp --device=eth0 --onboot=on
reboot
timezone Asia/Shanghai
services --enable="chronyd"
bootloader --location=mbr --boot-drive=vda
zerombr
clearpart --all --initlabel
autopart --type=lvm
%packages
@^minimal
@core
chrony
%end
%addon com_redhat_kdump --disable --reserve-mb='auto'
%end
%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end
安装全新的虚拟机
kvm_install(){
set -ue
set -o pipefail
ls /home/kvm/{ks,virtualhost,virtual-img} 1>/dev/null 2>&1 || mkdir -p /home/kvm/{virtualhost,virtual-img}
KVM_HOME=/home/kvm
KVM_ISO=${KVM_HOME}/iso/centos7.iso
KVM_KS_FILE=${KVM_HOME}/ks.cfg
KVM_IMG_DIR=${KVM_HOME}/virtual-img
OS_TYPE="linux"
DEF_OS_VARIANT="rhel7"
DEF_VM_NAME="centos$(date +%Y%m%dT%H%M%S)"
DEF_MEM_SIZE=1024
DEF_VCPUS=1
DEF_DISK_SIZE=10G
echo "输入将要创建的KVM虚拟机名称,不是主机名哦"
read -p "默认值${DEF_VM_NAME}>>:" VM_NAME
echo "输入将要创建的服务器主机名"
read -p "默认 localhost>>:" HOST_NAME
read -p "输入虚拟机 CPU 核心数默认 1 示例:2>>:" VCPUS
echo "输入虚拟机内存大小,默认1024M,不支持其他单位"
read -p "只需要添数字即可>>:" MEM_SIZE
echo "输入虚拟机使用的磁盘容量"
read -p "默认 10G,[示例写法:15G]>>:" DISK_SIZE
VM_NAME=${VM_NAME:-$DEF_VM_NAME}
HOST_NAME=${HOST_NAME:-localhost.localdomain}
VCPUS=${VCPUS:-$DEF_VCPUS}
MEM_SIZE=${MEM_SIZE:-$DEF_MEM_SIZE}
DISK_SIZE=${DISK_SIZE:-$DEF_DISK_SIZE}
OS_VARIANT=${OS_VARIANT:-$DEF_OS_VARIANT}
new_disk=${KVM_IMG_DIR}/${VM_NAME}.qcow2
if [[ ! "${DISK_SIZE}" =~ G$ ]] || [[ ! "${DISK_SIZE::-1}" =~ ^[0-9]+$ ]]
then
echo "格式不正确,正确示例:20G"
exit
fi
if [ ! -f "${new_disk}" ];then
qemu-img create -f qcow2 ${new_disk} ${DISK_SIZE}
fi
virt-install -v \
--arch x86_64 --virt-type kvm \
--name ${VM_NAME} \
--memory ${MEM_SIZE} \
--vcpus ${VCPUS} \
--os-type ${OS_TYPE} \
--location ${KVM_ISO} \
--network default \
--graphics none \
--os-variant ${OS_VARIANT} \
--initrd-inject "${KVM_KS_FILE}" \
--extra-args "ks=file:/ks.cfg \
console=tty0 console=ttyS0,115200n8 \
hostname=${HOST_NAME}" \
--disk ${new_disk},cache=writeback,io=threads,bus=virtio
}