简体   繁体   中英

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.

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, eg 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM