【问题标题】:variable scope in chef LWRPsChef LWRP 中的可变范围
【发布时间】:2015-05-19 18:24:57
【问题描述】:

我有以下问题,我认为是因为我不了解 Chef LWRP 中的变量范围。

您可以查看 https://github.com/jkleinlercher/chef_problems 的食谱并简单地测试一下厨房的行为。

尽管我定义了以下非常相似的资源,但我认识到,“颜色”属性继承自之前定义的资源。属性“颜色”默认为“['蓝色']”,并且在提供程序中,元素“洋红色”被添加到数组中。但是,第二个和第三个资源从前一个资源继承了整个数组。这对我来说很奇怪......

recipes/default.rb 中的资源定义:

chef_problems_problem1 "test1" do
     address "myaddress1"
     action :install
end

chef_problems_problem1 "test2" do
     address "myaddress2"
     action :install
end

chef_problems_problem1 "test3" do
    address "myaddress3"
    action :install
end

在厨房收敛的输出中,您会看到变量 new_resource.colors 继承了先前资源的值:

     * chef_problems_problem1[test1] action install
   new_resource.colors at the beginning: ["blue"]

   Values of local variables:
   address: myaddress1
   colors: ["blue"]

   adding magenta to local variable colors

   colors after adding magenta: ["blue", "magenta"]
   new_resource.colors at the end: ["blue", "magenta"]


     * chef_problems_problem1[test2] action install
   new_resource.colors at the beginning: ["blue", "magenta"]

   Values of local variables:
   address: myaddress2
   colors: ["blue", "magenta"]

   adding magenta to local variable colors

   colors after adding magenta: ["blue", "magenta", "magenta"]
   new_resource.colors at the end: ["blue", "magenta", "magenta"]


     * chef_problems_problem1[test3] action install
   new_resource.colors at the beginning: ["blue", "magenta", "magenta"]

   Values of local variables:
   address: myaddress3
   colors: ["blue", "magenta", "magenta"]

   adding magenta to local variable colors

   colors after adding magenta: ["blue", "magenta", "magenta", "magenta"]
   new_resource.colors at the end: ["blue", "magenta", "magenta", "magenta"]

也许你能帮我找出问题出在哪里。

【问题讨论】:

    标签: ruby chef-infra lwrp


    【解决方案1】:

    似乎默认值被传递给每个新资源,但没有为每个新资源克隆。结果,数组(不是它的内容)是默认值。如果您向此数组添加内容,则预计每个使用默认属性值的提供者都将拥有完整的数组。

    就个人而言,它认为这有点出乎意料。我认为您会为每个新资源传递默认值的克隆,但这里似乎并非如此。现在,如果您将新数组传递给资源定义中的颜色属性,那么您将不会看到相同的效果。

    但是,这不是范围问题。这取决于如何将默认值传递给资源的每个新实例。

    来自约翰内斯的更新:

    原来这个问题已经在https://tickets.opscode.com/browse/CHEF-4608讨论过,但没有修复。您可以使用此票证中描述的解决方法,也可以简单地在提供程序操作中创建一个新数组,例如

    colors = Array.new(new_resource.colors)
    

    然后使用新数组,不要触及原始属性。

    【讨论】:

    • 啊有趣。这和tickets.opscode.com/browse/CHEF-4608一样吗?
    • 确实如此。如前所述,它本身并不是一个真正的错误,但肯定会让许多人感到惊讶。
    • 谢谢!你真的帮了我很多!
    • NP。希望我有更好的消息。但我很高兴这张票能为您提供解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    相关资源
    最近更新 更多