跳至主要內容

Vagrant批量创建虚拟机

LincZero小于 1 分钟

Vagrant批量创建虚拟机

Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/jammy64"
  
  (1..3).each do |i|
    config.vm.define "node-#{i}" do |node|
      node.vm.provision "shell",
      inline: "echo hello from node #{i}"
    end
  end
  
end

我们可以通过数组来定义多个虚拟机的配置。

vm_list = [
  { # hash map
    "name" => "node-1",
    "cpu" => "2",
    "mem" => "2048",
    "ip_addr" => "192.168.56.10"
  },
  {
    "name" => "node-2",
    "cpu" => "1",
    "mem" => "1024",
    "ip_addr" => "192.168.56.11"
  },
  {
    "name" => "node-3",
    "cpu" => "1",
    "mem" => "1024",
    "ip_addr" => "192.168.56.12"
  }
]

Vagrant.configure(2) do |config|

   config.vm.box = "ubuntu/jammy64"

   vm_list.each do |item|
        config.vm.define item["name"] do |node|

            node.vm.provider "virtualbox" do |vbox|
              vbox.name = item["name"];  # 虚拟机名称
              vbox.memory = item["mem"]; # 内存
              vbox.cpus = item["cpu"];   # CPU
            end
            # 设置hostanme
            node.vm.hostname = item["name"]
            # 设置IP
            node.vm.network "private_network", ip: item["ip_addr"]

        end
    end

end

命令后面加虚拟机的名字,可以单独操作虚拟机:

vagrant up node-1
vagrant halt node-1
vagrant reload node-1
vagrant destroy node-1
vagrant provision node-1

SSH的私钥也分别存放在.vagrant虚拟机名对应的目录下

ssh vagrant@192.168.56.10 -i .vagrant/machines/k3s-server/virtualbox/private_key

.vagrant

bundler

machines

k3s-agent1

秘钥

k3s-agent2

秘钥

k3s-server

秘钥