Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to template Vagrantfile using Ruby?

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!

like image 462
Valter Silva Avatar asked Mar 13 '23 02:03

Valter Silva


1 Answers

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
like image 56
Frederic Henri Avatar answered Mar 24 '23 21:03

Frederic Henri