user2835733
user2835733

Reputation: 15

Chef Ruby -- are Loops within the variables for template possible?

I have spent already a long deal of time trying to figure out how to do this, I have also investigated but I have not found the right approach to it...?

basically I am trying to do something like the following:

types = ['type1','type2']
classes = ['class1','class2']

classes.each do |class|
    types.each do |type|

        template "/files/filename.txt" do
          source "source_file.erb"
          owner "root"
          group "root"
          mode "0440"
          variables({
            :pri_areas => node['area']['#{type}']['#{class}'],
            :rev_areas => node['area']['#{type}']['#{class}']
        })
        end

    end
end

Obviously I got all the attributes already defined so everything looks all right from that front.. I still cannot manage to get a loop with arrays like that withing the variables? Maybe another different approach?

Any ideas/help?

Thanks very much.

Upvotes: 0

Views: 840

Answers (1)

Holger Just
Holger Just

Reputation: 55898

Your code has some issues which you need to fix before it will properly work.

At first, class is a reserved keyword in Ruby and thus can't be used as a variable name. You should use another one, e.g. klass.

Secondly, class (or klass) as well as type are already strings inside your loop. Thus you don't need to attempt string interpolation. You can directly use this:

variables({
  :pri_areas => node['area'][type][klass],
  :rev_areas => node['area'][type][klass]
})

The reason why your string interpolation didn't work is that ruby knows two different kinds of String literals: ones with " and ones with '. The difference is that the ones delimited with ' do not allow string interpolation and generally do not interpret anything inside then as something else than the literal written string. Only in Strings delimited by ", you can perform string interpolation like "#{foo}" and use escape sequences like \n.

Upvotes: 2

Related Questions