在不更改Vagrantfile的情况下,在Vagrant的同一VM上运行动态数量的Shell Provisioning?

时间:2018-09-25 01:37:04

标签: ruby vagrant yaml vagrantfile

我正在编写一个Vagrantfile来设置VM。我不想在Vagrantfile中硬编码一些配置参数,例如内存和CPU数量。结果,我正在使用一个YAML文件,该文件已加载到Vagrantfile中以存储这些配置参数。 YAML文件中存储的一件事是要运行的Shell Provisioner脚本列表。例如:

---
machine_config:
  mem: 2048
  cpus: 2
  provisioners:
    -name: shell-script-1
     path: <path-to-shell-script-1>
    -name: shell-script-2
     path: <path-to-shell-script-2>
---

供应商的数量不是先验的:在上面的YAML中有两个,但这仅是示例。我想有一个Vagrantfile,它可以运行YAML文件中的所有预配器。我的意思是我希望能够在不触摸Vagrantfile的情况下向YAML文件添加/删除预配器,但是Vagrantfile应该正确运行YAML文件中的所有预配器。我在Google上进行了搜索,其中有很多示例说明了如何在动态数量的VM上运行相同的,经过硬编码的资源调配器,但是找不到与我有关的问题。

用伪vagrantfile语法编写的我想做的是:

require "yaml"

current_dir = File.dirname(File.expand_path(__FILE__))
yaml_config = YAML.load_file("#{current_dir}/machine_config.yaml")
machine_config = yaml_config["machine_config"]
additional_scripts = machine_config["provisioners"]

Vagrant.configure("2") do |config|
  config.vm.box = <vm-box-to-use>

  for each item $script in additional_scripts do 
    config.vm.provision "shell", path: $script["path"] 
  end

end

其中,machine_config.yaml是一个YAML文件,类似于该问题的第一个示例中的文件,而$ script是一个变量,该变量在循环的每次迭代中都在machine_config.yaml中描述的文件中包含一个供应器。最后一点,我对Ruby和Ruby的语法一无所知(也许对有此知识的人来说,我的问题的答案是微不足道的,但我无法通过谷歌搜索找到它)。

1 个答案:

答案 0 :(得分:1)

以下将起作用

require "yaml"

current_dir = File.dirname(File.expand_path(__FILE__))
yaml_config = YAML.load_file("#{current_dir}/machine_config.yaml")
machine_config = yaml_config["machine_config"]

Vagrant.configure("2") do |config|
  config.vm.box = "<vm-box-to-use>"

  machine_config["provisioners"].each do |script|
    config.vm.provision "shell", name: script['name'], path: script['path']
  end

end
相关问题