【问题标题】:Chef Ruby -- are Loops within the variables for template possible?Chef Ruby——模板变量中的循环是否可能?
【发布时间】:2013-10-02 01:04:41
【问题描述】:

我已经花了很长时间试图弄清楚如何做到这一点,我也进行了调查,但我没有找到正确的方法......?

基本上我正在尝试执行以下操作:

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

显然我已经定义了所有属性,所以从前面看一切都很好.. 我仍然无法设法获得带有变量的数组的循环? 也许是另一种不同的方法?

有什么想法/帮助吗?

非常感谢。

【问题讨论】:

    标签: ruby chef-infra


    【解决方案1】:

    您的代码有一些问题需要修复才能正常工作。

    起初,class 是 Ruby 中的保留关键字,因此不能用作变量名。您应该使用另一个,例如klass.

    其次,class(或klass)以及type 已经是循环中的字符串。因此,您不需要尝试字符串插值。你可以直接使用这个:

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

    字符串插值不起作用的原因是 ruby​​ 知道两种不同类型的字符串文字:带有 " 的字符串和带有 ' 的字符串。不同之处在于,以' 分隔的那些不允许字符串插值,并且通常不会将内部的任何内容解释为文字写入字符串之外的其他内容。只有在以" 分隔的字符串中,您可以像"#{foo}" 那样执行字符串插值,并使用像\n 这样的转义序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多