0

我有以下问题,我认为这是因为我不了解 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

在 kitchen blend 的输出中,您会看到变量 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"]

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

4

1 回答 1

0

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

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

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

来自约翰内斯的更新:

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

colors = Array.new(new_resource.colors)

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

于 2015-05-11T14:38:10.693 回答