2

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:

Code

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
    end
end 

1 Answer 1

2

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|
  # ...
end

Or you can switch to this:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answar, that worked. How can I set user group with that command on subfolers? recursive true doesn't set user group on subfolders below /var/lib/temp and /opt/chef/library. Equiqvalent command to chown -R user:group /var/lib/temp/* in Linux.
That's a whole other question, so best to split that out as a separate thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.