ZvL
ZvL

Reputation: 803

Trying to loop over hash for Vagrant boxes, failing

Ok, i'm very new to Ruby (i come from PHP, Symfony2 and AngularJS) and relatively new when it comes to properly writing Vagrantfiles. I'm trying to create a multi-machine environment while trying to stick to DRY principles.

As i read that Vagrantfiles understand Ruby syntax, i looked up the way Ruby defines associative arrays. This happened to be quite easy, apparently not.

My Vagrantfile:

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

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

#hash for boxes: 'box_name' => 'last_ip_octet'
boxes = {
        'frontend' => '10',
        'qp' => '11'
}


Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

config.vm.box = "chef/ubuntu-14.04"

#All machines, see the hash defined in top of the Vagrantfile for all the boxes
  boxes.each do |key, value|
    config.vm.define "#{key}.qp" do |#{key}_qp|
        #{key}_qp.vm.network "private_network", ip: "192.168.51.#{value}"
        #{key}_qp.vm.provision "shell", path: "../provisioning/agentinstall.sh"
        #{key}_qp.vm.synced_folder "./share/#{key}.qp", "/var/www/html"
    end
  end
end                                           

My problem reads as follows:

There is a syntax error in the following Vagrantfile. The syntax error
message is reproduced below for convenience:

/Users/Zowie/Documents/vagrant/project/temp/Vagrantfile:30: syntax error,           unexpected keyword_end, expecting '|'
end     
   ^        

Unfortunately, i can't find any info on using Hashes or anything similar in Vagrantfiles. I really hope you can help me out, because i'd not feel good while writing a super-long Vagrantfile with a lot of repetitions...

Thanks in advance!

Upvotes: 2

Views: 3604

Answers (1)

ZvL
ZvL

Reputation: 803

The Stackoverflow website answered my question for me! Thanks to Stackoverflow's code block feature, i noticed that my machine-specific configurations were commented out because i used a '#'.

I fixed it by using the following syntax in my loop (which is also easier to read):

  boxes.each do |key, value|
    config.vm.define "#{key}.qp" do |node|
        node.vm.network "private_network", ip: "192.168.51.#{value}"
        node.vm.provision "shell", path: "../provisioning/agentinstall.sh"
        node.vm.synced_folder "./share/#{key}.qp", "/var/www/html"
    end
  end

Upvotes: 2

Related Questions