Installing KVM Guests With virt-install On CentOS6 [Automatic Installation]

在CentOS机器上自动化安装KVM虚拟机

内容主要包括初始化KVM环境,利用KS自动化安装系统, 所有东西都在代码里面了,自己看

1. 初始化系统环境,部署KVM依赖包

sudo yum -y install kvm qemu-kvm libvirt python-virtinst bridge-utils virt-clone

2. 设置桥接网卡

代码示例,将eth0转换为br0

#!/bin/bash
HOST_IP_eth0=$(ifconfig eth0 | grep "inet addr"| tr ':' ' '  | awk '{print $3}')  
HOST_NETMASK_eth0=$(ifconfig eth0 | grep "inet addr"| tr ':' ' '  | awk '{print $7}')

HOST_GW=$(route -n | grep 'UG[ \t]' | awk '{print $2}')

setup_birdge_eth0 () {  
   FILE_IFCFG_BR0="/etc/sysconfig/network-scripts/ifcfg-br0"
   cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-br0
DEVICE="br0"  
ONBOOT=yes  
BOOTPROTO=static  
NM_CONTROLLED="yes"  
TYPE=Bridge  
EOF  
    echo IPADDR=${HOST_IP_eth0}  >> $FILE_IFCFG_BR0
    echo NETMASK=${HOST_NETMASK_eth0} >> $FILE_IFCFG_BR0
    echo GATEWAY=${HOST_GW} >> $FILE_IFCFG_BR0

    FILE_IFCFG_ETH0="/etc/sysconfig/network-scripts/ifcfg-eth0"
    rm -f ${FILE_IFCFG_ETH0}
    cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"  
ONBOOT=yes  
BRIDGE=br0  
EOF  
}

示例文件如下:

[root@bj-office-01 network-scripts]# cat ifcfg-eth0
DEVICE="eth0"  
ONBOOT=yes  
BRIDGE=br0  
[root@bj-office-01 network-scripts]# cat ifcfg-br0
DEVICE="br0"  
ONBOOT=yes  
BOOTPROTO=static  
NM_CONTROLLED="yes"  
TYPE=Bridge  
IPADDR=192.168.4.100  
NETMASK=255.255.252.0  
GATEWAY=192.168.4.1  

3. 搭建http服务器,挂载iso镜像

mount -o loop /data2/iso/centos7.iso /var/www/html/centos7/  

4. 编写KS文件,用于自动化安装操作系统。

例子:

reboot --eject  
install  
text  
lang en_US.UTF-8  
keyboard us  
network --bootproto=dhcp --onboot=on --hostname=admaster  
rootpw nidaye  
firewall --disabled  
authconfig --enableshadow --passalgo=sha512  
selinux --disabled  
timezone --utc Asia/Shanghai  
url --url http://192.168.4.100/centos7/  
clearpart --all --initlabel --drives=vda  
bootloader --location=mbr --driveorder=vda  
part /boot --fstype=ext4 --size=1000 --ondisk=vda  
part / --fstype=ext4 --size=1 --grow --ondisk=vda

%packages
@base
@core
@development
@network-tools
@system-admin-tools
%end

5. 通过virt-install安装kvm虚拟机

代码示例:

#!/bin/bash

#Usage: ./virt_install.sh domain_name
#Author: Zez

IMG_DIR=/data2  
IMG_SIZE=500G  
IMG_LOC=${IMG_DIR}/vm-images/

qemu-img create -f qcow2 $IMG_LOC/${1}.qcow2 ${IMG_SIZE}

virt-install \  
--name ${1} \
--ram 4096 \
--disk path=$IMG_LOC/${1}.qcow2,size=500,bus=virtio,driver_type=qcow2 \
--vcpus 2 \
--os-type linux \
--network bridge:br0,model=virtio \
--graphics none \
--console pty,target_type=serial \
--location 'http://192.168.4.100/centos7/' \
--extra-args 'ks=http://192.168.4.100/ks.cfg console=ttyS0,115200n8 serial'