如何在Chef LWRP定义中实现动态属性默认值 [英] How to implement a dynamic attribute default in chef LWRP definition

查看:57
本文介绍了如何在Chef LWRP定义中实现动态属性默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用3个参数来定义轻量级资源,其中2个是基本/基本参数,第3个是这两个参数的组合。我还想提供自定义第三个参数的可能性。例如:

I would like to be able to define a lightweight resource with let's say 3 parameters, two of them being basic/elementary parameters and the third being a combination of these two. I would also like to provide a possibility of customization of the third parameter. For example:

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

How to modify following code to achieve above behaviour for the full_name attribute:

资源定义:

actions :install

attribute :name, :kind_of => String, :name_attribute => true
attribute :version, :kind_of => String
attribute :full_name, :kind_of => String

提供者定义:

action :install do
    Chef::Log.info "#{new_resource.full_name}"
end

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

I would like to see different outputs for different resource directives, e.g.:

resource "abc" do
    version "1.0.1"
end

将产生 abc-1.0.1 ,但是:

resource "def" do
    version "0.1.3"
    full_name "completely_irrelevant"
end

会导致 completely_irrelevant

是否有可能在资源定义中定义此行为(可能通过 default 参数)还是只能在提供程序定义中做到这一点?如果第二个为真,那么我可以将计算出的值存储在 new_resource 对象的 full_name 属性中(该类似乎错过 full_name = 方法定义)还是必须将其存储在本地变量中?

Is there a possibility to define this behaviour in the resource definition (probably through the default parameter) or I am able to do it in provider definition only? If the second is true, then can I store the calculated value in the new_resource object's full_name attribute (the class seems to miss the full_name= method definition) or I have to store it in a local variable?

更新

由于Draco的提示,我意识到我可以在资源文件中创建访问器方法并计算 full_name 在请求时即时价值。我希望有一个更清洁的解决方案,但是比在行动实施中对其进行计算要好得多。

Thanks to Draco's hint, I realized that I can create an accessor method in the resource file and calculate the full_name value on the fly when requested. I would prefer a cleaner solution but it's much better than calculating it in action implementation.

厨师版本
厨师:10.16.4

Chef version Chef: 10.16.4

推荐答案

在构造函数中设置@full_name,类似于在Chef<中提供默认操作。 0.10.10,如用Wiki写一样,不起作用,因为@版本尚未设置。

Setting @full_name in constructor, similar to providing default action in chef < 0.10.10, as written in wiki, does not work, because @version is not set at that point yet.

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

因此,我们必须通过添加

So we have to overwrite full_name method in resource by adding

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

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

into resource definition. That works. Tested.

这篇关于如何在Chef LWRP定义中实现动态属性默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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