如何在 Vagrant 中 运行 命令块一次

How to run command block in Vagrant once

如何 运行 Vagrantfile 中的命令块只执行一次。尝试使用 if 大小写,但没有成功。

流浪文件:

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

$hosts = {
    "node-1" => { memory: 1024, cpus: 2 },
    "node-2" => { memory: 4096, cpus: 2 }
}

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|      
  $hosts.each_with_index do |(hostname, parameters), index|  
    config.vm.define vm_name = hostname do |vm_config|
      vm_config.vm.hostname = hostname

      config.vm.provision "shell", inline: "echo index=#{index}"

      if index == 0
        config.vm.provision "shell", path: "./bootstrap-scripts/node-1.sh"
      end

    end
  end
end

控制台结果:

==> node-1: Importing base box 'generic/ubuntu1804'...
...
==> node-1: Running provisioner: shell...
    node-1: Running: inline script
    node-1: index=0

==> node-2: Importing base box 'generic/ubuntu1804'...
...
==> node-2: Running provisioner: shell...
    node-2: Running: inline script
    node-2: index=0
==> node-2: Running provisioner: shell...
    node-2: Running: inline script
    node-2: index=1

目标是 运行 “./bootstrap-scripts/control.sh” 脚本仅用于第一台机器。

来自vagrant documentation

The inner portion of multi-machine definitions and provider overrides are lazy-loaded. This can cause issues if you change the value of a variable used within the configs ...

each_with_index 的内部行为可能触发记录的陷阱,这就是为什么您的 node-2 循环遍历两个索引。因此,请尝试在 if 中使用节点名称。

您还需要使用 vm_config 而不是 config 是您希望供应商为每个节点申请。