Chef库中的访问节点属性 [英] Access Node attributes in Chef Library

查看:51
本文介绍了Chef库中的访问节点属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Chef库,


  • 提供一些命名空间函数

  • 访问节点的属性



该库旨在与外部系统接口并从中检索一些输入。我需要访问节点属性,以允许用户覆盖从外部系统接收的输入:



所需用法(配方)



 输入= MyLib.get_inputs 



图书馆(我现在所拥有的)



这是受这些文档

  class Chef :: Recipe :: MyLib 
def self.get_inputs
bover_inputs = node.fetch(:mylib,Hash.new).fetch(:override_inputs,nil)

除非override_inputs.nil?
return overlay_inputs
end

#做东西并返回输入(这里没有问题)
#...
end
end



问题



现在我得到:

  Chef :: Recipe :: Scalr:Class 


解决方案

除非您将其传递给库中的节点对象,否则您无权访问该对象。初始化程序:

  class MyHelper 
def self.get_inputs_for(node)
#您的代码会正常工作
结束
结束

然后您将其称为:

  inputs = MyHelper.get_inputs_for(node)

或者,您可以创建一个模块并将其混合到Chef Recipe DSL中:

  module MyHelper 
def get_inputs
#相同的代码,但是您会得到节点,因为这是一个混合
end
结束

Chef :: Recipe.send(:include,MyHelper)

然后您就可以在食谱中访问 get_inputs 方法:

 输入= get_inputs 

请注意,这是实例方法与类方法。



简而言之,除非作为参数给出,否则库无权访问 node 对象。如果将模块混合到Recipe DSL中,则将进行。此外,节点对象实际上是一个实例变量,因此它在类级别不可用(即 self。 / code>)。


I'd like to create a Chef library that:

  • Provides a few namespaced functions
  • Accesses the node's attributes

That library is meant to interface with an external system and retrieve some inputs from there. I need to access the node attributes to allow the user to override the inputs received from the external system:

Desired Usage (Recipe)

inputs = MyLib.get_inputs

Library (What I have now)

This is inspired by those docs.

class Chef::Recipe::MyLib
  def self.get_inputs
    override_inputs = node.fetch(:mylib, Hash.new).fetch(:override_inputs, nil)

    unless override_inputs.nil?
      return override_inputs
    end

    # Do stuff and return inputs (no problem here)
    # ...
  end
end

Problem

Right now I'm getting:

undefined local variable or method `node' for Chef::Recipe::Scalr:Class

解决方案

You don't have access to the node object in a library unless you pass it into the initializer:

class MyHelper
  def self.get_inputs_for(node)
    # Your code will work fine
  end
end

Then you call it with:

inputs = MyHelper.get_inputs_for(node)

Alternative, you can to create a module and mix it into the Chef Recipe DSL:

module MyHelper
  def get_inputs
    # Same code, but you'll get "node" since this is a mixin
  end
end

Chef::Recipe.send(:include, MyHelper)

Then you have access to the get_inputs method right in a recipe:

inputs = get_inputs

Notice this is an instance method versus a class method.

In short, libraries don't have access to the node object unless given as a parameter. Modules will, if they are mixed into the Recipe DSL. Additionally, the node object is actually an instance variable, so it's not available at the class level (i.e. self.).

这篇关于Chef库中的访问节点属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆