vmos vmos - 2 months ago 11
Ruby Question

How do I reuse variables in quoted line in a Vagrantfile?

I'm putting together a Vagrantfile that can be used to spin up multiple VMs, it mostly works apart from the bit where I need to tell ansible which playbook to use. This is being imposed on top of an existing structure so there's little scope to change file locations and that.

Here's an extract of the relevant bits from my

Vagrantfile
:

hosts = [
{ name: 'myhost01', hostname: 'vg-myhost01', ip: '172.172.99.99', memory:'512', cpu: 1, box: 'centos', port_forward: [] },
]

config.vm.provision :ansible do |ansible|
ansible.playbook = ['install/mydir/install_', :name, '.yml']
end


Basically I'm trying to figure out how to get it to end up with a setting like

ansible.playbook = 'install/mydir/install_myhost01.yml'


but I can't seem to get the right syntax to get it to recognise
:name
as a variable in that context. It either tries to run
install_.yml
,
install_name.yml
or most commonly gives the error:


`initialize': no implicit conversion of Symbol into String (TypeError)


Any suggestions?

Answer

It's more a question about Ruby syntax. You can use:

ansible.playbook = 'install/mydir/install_' + name + '.yml'

or (thanks to Frédéric Henri)

ansible.playbook = "install/mydir/install_#{name}.yml"

To reference the value from the hash (per OP's own suggestion):

ansible.playbook = "install/mydir/install_#{host[:name]}.yml"
Comments