#!/usr/bin/env bash
set -ue
set -o pipefail
# 创建相关目录
ls /home/kvm/{ks,virtualhost,virtual-img} 1>/dev/null 2>&1 || mkdir -p /home/kvm/{ks,virtualhost,virtual-img}
# 此程序的变量
KVM_HOME=/home/kvm
KVM_ISO=${KVM_HOME}/iso/CentOS-7-x86_64-Minimal-1708.iso
KVM_KS_FILE=${KVM_HOME}/ks/ks.cfg
KVM_IMG_DIR=${KVM_HOME}/virtual-img
KVM_HOST_DIR=${KVM_HOME}/virtualhost
OS_TYPE="linux"
DEF_OS_VARIANT="rhel7"
DEF_VM_NAME="centos$(date +%Y%m%dT%H%M%S)"
# 设置默认内存大小 1024 M,这个单位是固定的 M,不支持其他单位
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
# 桥接模式,前提是你已经建立好了网桥
# --network bridge=virbr0 --network bridge=docker0 \
# end