如何一键批量创建kvm虚拟机?

脚本如下

#!/usr/bin/env bash
[[ -n $DEBUG ]] && set -x
set -eou pipefail

useage(){
  cat <<"EOF"
USAGE:
    vminit BOX NAME START END MEM CPU IPBASE [DISKS...]
    eg:
      vminit centos-7-1905.1-libvirt demohost 192.168.50 2 10 2 2048 20G 10G
EOF
}

exit_err() {
   echo >&2 "${1}"
   exit 1
}

if [ $# -lt 7 ];then
    useage
    exit 1
fi

BOX=$1
NAME=$2
IPBASE=$3
START=$4
END=$5
CPU=$6
MEM=$7
shift 7
DISKS=$@

mkdir -p "${NAME}"
cd "${NAME}"

net_exists=0
for net in $(virsh net-list --all --name | xargs -r ); do
  if [[ x"$NAME" == x"$net" ]];then
    net_exists=1
  fi
done

ip2mac(){
  local MAC=$1
  local IP=$2
  for index in {1..4}; do
      ipi=$(echo "${IP}" | cut -d "." -f "${index}")
      maci=$(echo "obase=16;${ipi}" | bc)
      MAC="${MAC}"':'"${maci}"
  done
  echo "${MAC}"
}

if [[ $net_exists -eq 0 ]];then
cat >network.xml <<EOF
<network ipv6="yes">
  <name>${NAME}</name>
  <forward mode="nat">
    <nat>
      <port start="1024" end="65535"/>
    </nat>
  </forward>
  <bridge name="${NAME}br" stp="on" delay="0"/>
  <ip address="${IPBASE}.1" netmask="255.255.255.0">
    <dhcp>
      <range start="${IPBASE}.2" end="${IPBASE}.254"/>
EOF

for ((i=2;i<=254;i++)); do
IP="${IPBASE}.$i"
MAC=$(ip2mac "50:50" "${IP}")
cat >>network.xml <<EOF
      <host mac="${MAC}" ip="${IP}"/>
EOF
done

cat >>network.xml <<EOF
    </dhcp>
  </ip>
</network>
EOF

virsh net-define --file ./network.xml
fi

cat >Vagrantfile <<EOF
# -*- mode: ruby -*-
# vi: set ft=ruby :

def ip2mac(prefix, str_ip)
	@mac=prefix
	str_ip.split('.').each do |k|
		k="%02x" % k
		@mac=@mac+":"+k.to_s
	end
	return @mac
end

Vagrant.configure("2") do |config|
  (${START}..${END}).each do |i|
    config.vm.define "$NAME#{i}" do |node|
      # node.ssh.username = 'root'
      # node.ssh.password = 'vagrant'
      node.ssh.insert_key = true
      node.vm.box = '${BOX}'
      node.vm.synced_folder '.', '/vagrant', disabled: true
      node.vm.provider :libvirt do |domain|
        domain.driver = 'kvm'
        domain.memory = ${MEM}
        domain.cpus = ${CPU}
        domain.nested = true
        domain.management_network_name = "${NAME}"
        domain.management_network_address = "${IPBASE}.0/24"
        domain.management_network_mac = ip2mac("50:50","${IPBASE}.#{i}")
EOF

for DISK in ${DISKS};do
cat >>Vagrantfile <<EOF
        domain.storage :file, :size => '${DISK}', :bus => 'virtio'
EOF
done

cat >>Vagrantfile <<EOF
      end
      node.vm.provision :shell, :path => 'provision.sh'
    end
  end
end
EOF

cat >provision.sh <<EOFF
#!/bin/bash
sed -ri 's/^PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
cat >>/etc/ssh/sshd_config <<EOF
PermitRootLogin yes
UseDNS no
systemctl restart sshd
EOF
EOFF

vagrant up

使用方法

使用vmbox(见https://www.cnblogs.com/futuretea/p/12009678.html)快速下载centos-7-1905.1-libvirt.box

vmbox centos 7 1905.1 libvirt
vagrant box add centos-7-1905.1-libvirt.box centos-7-1905.1-libvirt

以centos-7-1905.1-libvirt为基础box
定义了一个名为demohost的网络(默认的vagrant-libvirt网络ip为dhcp分配,demohost的网络加了mac地址绑定)
在demohost网络内创建了ip为192.168.50.10~192.168.50.19的10台虚拟机
每台虚拟机,2核cpu,2G内存,除了系统盘外额外添加两块硬盘,一块20G,一块10G

vminit centos-7-1905.1-libvirt demohost 192.168.50 10 19 2 2048 20G 10G

效果

❯ vagrant status
Current machine states:

demohost10                running (libvirt)
demohost11                running (libvirt)
demohost12                running (libvirt)
demohost13                running (libvirt)
demohost14                running (libvirt)
demohost15                running (libvirt)
demohost16                running (libvirt)
demohost17                running (libvirt)
demohost18                running (libvirt)
demohost19                running (libvirt)

This environment represents multiple VMs. The VMs are all listed
above with their current state. For more information about a specific
VM, run `vagrant status NAME`.


took 4s 

❯ vagrant ssh demohost10 
[vagrant@localhost ~]$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 50:50:c0:a8:32:0a brd ff:ff:ff:ff:ff:ff
    inet 192.168.50.10/24 brd 192.168.50.255 scope global noprefixroute dynamic eth0
       valid_lft 2790sec preferred_lft 2790sec
    inet6 fe80::5250:c0ff:fea8:320a/64 scope link 
       valid_lft forever preferred_lft forever

没有多余的默认网卡,当然如果你想定义多网卡也是可以的,详见vagrant-libvirt文档

posted @ 2019-12-13 17:32  futuretea  阅读(694)  评论(0编辑  收藏  举报