Search code examples
rubyvagrantfile

How to render a YAML list in a Vagrantfile


I have a Vagrantfile which is referencing a YAML file to make multi-host configuration easier.

It's mostly working, but I'm using the Ansible provisioner and I need to reference a list/array for the ansible.groups item.

The YAML looks like this:

hosts:
  - host:
      provision:
        ansible:
          enable: yes
          playbook_path: webserver.yml
          groups:
            - web
            - vagrant
            - live            

I'm trying to reference it in the Vagrantfile using:

if host['provision']['ansible']['enable'] == true
  vmhost.vm.provision "ansible" do |ansible|
    ansible.verbose = "vv"
    ansible.config_file = "./ansible.cfg"
    ansible.playbook = host['provision']['ansible']['playbook_path']
    ansible.tags = host['provision']['ansible']['tags']
    ansible.groups = host['provision']['ansible']['groups']
  end
end

But this gives me this error when building the actual VMs:

undefined method `each_pair' for ["web", "vagrant", "dev"]:Array

I searched and haven't found anything that addresses ansible_groups specifically, though I have seen various patterns for reading lists/arrays in the Vagrantfile. Any ideas?


Solution

  • The Ansible groups are not supposed to be an array but a hash, mapping the groups to the server names. It should look like:

    hosts:
      - host:
          provision:
            ansible:
              enable: yes
              playbook_path: webserver.yml
              groups:
                web:
                  - machine1
                  - machine2
                vagrant:
                  - machine3
                  - machine4
                live:
                  - machine5
    

    See the documentation for more details on how this can be used.