user3580316 user3580316 - 11 months ago 64
Ruby Question

Chef using variables in a array

How can you use variables in an array in Chef. I am trying to create multiple folder with an array. However my code does not work:


variable1 = "/var/lib/temp"
variable2 = "/opt/chef/library"

%w{ #{variable1} #{variable2} }.each do |dir|
directory dir do
owner 'root'
group 'root'
mode '755'
recursive true
action :create

Answer Source

The %w{ ... } syntax is for declaring an array of words, and no interpolation is done. Since you want an array of pre-existing strings, you can do it this way by declaring a plain-old array:

[ variable1, variable2 ].each do |dir|
  # ...

Or you can switch to this:

%w[ /var/lib/temp /opt/chef/library ].each |dir|
  # ...

The second form makes a lot more sense since that's your intent. No need for intermediate variables.