第二节.使用Vagrant创建集群

1.下载box

$ vagrant box add ubuntu/trusty64

2.创建集群目录

$ mkdir vagrant-cluster

3.初始化集群目录

$ cd vagrant-cluster
$ vagrant init ubuntu/trusty64

4.编辑Vagrantfile $ vim Vagrantfile

Vagrant.configure("2") do |config|
    # The most common configuration options are documented and commented below.
    # For a complete reference, please see the online documentation at
    # https://docs.vagrantup.com.

    # Every Vagrant development environment requires a box. You can search for
    # boxes at https://atlas.hashicorp.com/search.
    (0..3).each do |i|

        config.vm.define "node#{i}" do |node|

            #  设置虚拟机的Box
            node.vm.box = "ubuntu/trusty64"

            # 设置虚拟机的主机名
            node.vm.hostname="node#{i}"

            # 设置虚拟机的IP
            node.vm.network "public_network", bridge: "eno1", ip: "192.168.17.20#{i}"

            # VirtaulBox相关配置
            node.vm.provider "virtualbox" do |v|
                v.name = "node#{i}"
                v.memory = 1024
                v.cpus = 1
            end
        end
        if ARGV[0] == "up" && ! File.exist?("./disk1.vdi")
            # 运行脚本增加swap空间
            config.vm.provision "shell", path: "increase_swap.sh"
        end
    end
end

与创建单个虚拟机相比,创建多个虚拟机时多了一层循环,而变量i可以用于设置节点的名称与IP,使用#{i}取值:

(0..3).each do |i|

end

5.添加增加swap空间脚本

$ vim increase_swap.sh

#!/bin/sh

# swapfile的大小,单位Megabyte
swapsize=1024

# 检查swapfile文件是否存在
grep -q "swapfile" /etc/fstab

# if not then create it
if [ $? -ne 0 ]; then
  echo 'swapfile not found. Adding swapfile.'
  fallocate -l ${swapsize}M /swapfile
  chmod 600 /swapfile
  mkswap /swapfile
  swapon /swapfile
  echo '/swapfile none swap defaults 0 0' >> /etc/fstab
else
  echo 'swapfile found. No changes made.'
fi

# 输出结果至控制台
df -h
cat /proc/swaps
cat /proc/meminfo | grep Swap

可知,一共创建了四个虚拟机

6.创建虚拟机

$ vagrant up

results matching ""

    No results matching ""