How to template Vagrantfile using Ruby?

2019-07-11 21:32发布

I have several Vagrantfile, each one for a different provider, since Vagrant has a limitation that doesn't allow to make two or more provisions at the same time using the same Vagrantfile. So, I split into two or more Vagrantfiles, but my "body", my provisions scripts are the same for both, the only thing that changes is the provider block.

For example:

local_nagios/Vagrantfile

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

require 'yaml'
set = YAML.load_file '../../../settings.yaml'

Vagrant.configure(2) do |nagios|

  nagios.vm.provider :virtualbox do |provider, override|
    override.vm.box = 'ubuntu/trusty64'
    override.vm.hostname = 'nagios.company.com'
    override.vm.synced_folder '.', '/vagrant', disabled:true
    override.vm.network 'public_network', bridge:set['network_interface'], ip:set['dev_nagios_ip']

    provider.memory = 4096
    provider.cpus = 2
  end

  install = set['devops_home'] + '/vagrant/lib/install'
  nagios.vm.provision 'shell', path: install + '/basic'
  nagios.vm.provision 'shell', path: install + '/devops'

  step = set['devops_home'] + '/vagrant/server/nagios/steps'
  nagios.vm.provision 'shell', path: step + '/install', args: [set['nagios_password']]

end

digital_nagios/Vagrantfile

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

require 'yaml'
set = YAML.load_file '../../../settings.yaml'

Vagrant.configure(2) do |nagios|

  nagios.vm.provider :digital_ocean do |provider, override|
    override.vm.box = 'digital_ocean'
    override.vm.hostname = 'nagios.company.com'
    override.vm.synced_folder '.', '/vagrant', disabled:true
    override.ssh.private_key_path = '~/.ssh/id_rsa'

    provider.token = 'my-token'
    provider.image = 'ubuntu-14-04-x64'
    provider.region = 'fra1'
    provider.size = '4gb'
  end

  install = set['devops_home'] + '/vagrant/lib/install'
  nagios.vm.provision 'shell', path: install + '/basic'
  nagios.vm.provision 'shell', path: install + '/devops'

  step = set['devops_home'] + '/vagrant/server/nagios/steps'
  nagios.vm.provision 'shell', path: step + '/install', args: [set['nagios_password']]

end

I wonder if is possible to make a template from this. Or import my common area like this:

Vagrant.configure(2) do |nagios|

  nagios.vm.provider :digital_ocean do |provider, override|
    ...
  end

  import '../provision.rb'

end

I'm not familiar with Ruby, so any suggestion would be very appreciated!

1条回答
Fickle 薄情
2楼-- · 2019-07-11 22:05

you can do something like

Vagrant.configure(2) do |nagios|

  nagios.vm.provider :digital_ocean do |provider, override|
    ...
  end

  eval File.read("../Vagrantfile-common")

end
查看更多
登录 后发表回答