CHEF:设置资源在调用另一个(自定义)资源时最后运行一次

时间:2017-04-19 10:49:52

标签: chef chef-recipe

我编写了一个自定义资源sshd_allow_groups,它的操作会更改某些节点的属性,而这些属性用于创建/etc/sshd_config的模板默认配方(托管自定义资源)。但是,由于自定义资源通常是从其他烹饪书中调用的,因此我无法保证在对属性进行更改后将调用模板资源,从而产生需要2个主厨运行才能获得的模板资源。期望的改变。

我正在寻找一种方法来在调用资源之后触发模板资源并在最后运行(如果资源被多次调用)。 notifies不起作用,因为模板的操作不是:nothing,也不应该是,因为如果某个节点不需要资源,则仍需要编写模板。

我的自定义资源:

resource_name :sshd_allow_groups
property :group, String, name_property: true

default_action :append

action :append do
  currently = node['tom-ssh']['allow_groups']
  if currently
    if !currently.include?(group)
      node.normal['tom-ssh']['allow_groups'] = currently | [group]
    end
  else
    node.normal['tom-ssh']['allow_groups'] = [group]
  end
end

action :remove do
  currently = node['tom-ssh']['allow_groups']
  if currently && currently.include?(group)
    node.normal['tom-ssh']['allow_groups'] = currently - [group]
  end
end

另一个食谱应该像这样称呼:

sshd_allow_groups "bob" do
  action :append
end

2 个答案:

答案 0 :(得分:0)

在您的cookbook libraries目录中,在helpers.rb文件(docblog post)中:

module Sshd_allow_groups
  module Helpers
    def append(group)
      node.normal['tom-ssh']['allow_groups'] = node['tom-ssh']['allow_groups'] | [group]
    end

    def remove(group)
        node.normal['tom-ssh']['allow_groups'] = node['tom-ssh']['allow_groups'] - [group]
    end
  end
end

在你的食谱中称之为:

Sshd_allow_group::Helpers.append("new_group")

或者如果您绝对确定(并且应该重命名这些方法),您可以将辅助方法包含在Recipe DSL中:

::Chef::Recipe.send(:include, sshd_allow_groups::Helpers)

我已经简化了一些代码,因为我感觉不必进行额外的检查,如果tom-ssh属性不存在,您可能仍然会引发异常。

我会尝试在node.normal停留在节点上,即使您删除后来添加组的配方也是如此。有关属性here

的更多详细信息

答案 1 :(得分:0)

无法评论,所以需要发布作为答案..我试图按照示例tensibai给出的答案,我发现了一点点。直接调用辅助方法不适用于模块中定义的辅助方法。您需要创建append / remove方法类实例。在追加/删除前添加self.。然后这个调用将起作用:

Sshd_allow_group::Helpers.append("new_group")

或者您可以在类中定义辅助方法以使用实例方法,或在类中使用帮助程序。

相关问题