如何在chef LWRP定义中实现动态属性默认值

Dar*_*zak 5 ruby chef-infra

我希望能够定义一个轻量级资源,让我们说3个参数,其中两个是基本/基本参数,第三个是这两个参数的组合.我还想提供定制第三个参数的可能性.例如:

如何修改以下代码以实现full_name属性的上述行为:

资源定义:

actions :install

attribute :name, :kind_of => String, :name_attribute => true
attribute :version, :kind_of => String
attribute :full_name, :kind_of => String
Run Code Online (Sandbox Code Playgroud)

提供者定义:

action :install do
    Chef::Log.info "#{new_resource.full_name}"
end
Run Code Online (Sandbox Code Playgroud)

我想看到不同资源指令的不同输出,例如:

resource "abc" do
    version "1.0.1"
end
Run Code Online (Sandbox Code Playgroud)

会导致abc-1.0.1,但是:

resource "def" do
    version "0.1.3"
    full_name "completely_irrelevant"
end
Run Code Online (Sandbox Code Playgroud)

会导致completely_irrelevant.

是否有可能在资源定义中定义此行为(可能通过default参数),或者我只能在提供程序定义中执行此操作?如果第二个为真,那么我可以将计算出的值存储在new_resource对象的full_name属性中(该类似乎错过了full_name=方法定义)或者我必须将它存储在局部变量中吗?

更新

感谢Draco的提示,我意识到我可以在资源文件中创建一个访问器方法,并full_name在请求时动态计算值.我更喜欢更清洁的解决方案,但它比在行动实施中计算它要好得多.

厨师版 厨师:10.16.4

Dra*_*ter 3

在构造函数中设置 @full_name 类似于在 Chef < 0.10.10 中提供默认操作(如wiki 中所写),但不起作用,因为此时尚未设置 @version。

def initialize( name, run_context=nil )
  super
  @full_name ||= "%s-%s" % [name, version]
end
Run Code Online (Sandbox Code Playgroud)

所以我们必须通过添加来覆盖资源中的 full_name 方法

def full_name( arg=nil )
  if arg.nil? and @full_name.nil?
    "%s-%s" % [name, version]
  else
    set_or_return( :full_name, arg, :kind_of => String )
  end
end
Run Code Online (Sandbox Code Playgroud)

进入资源定义。这样可行。已测试。