How to implement a dynamic attribute default in chef LWRP definition

梦想的初衷 提交于 2019-12-05 08:33:47

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.

attribute :full_name, :kind_of => String, default => lazy {|r| "#{r.name}-#{r.version}" }

After fighting this for some time, I found this to work cleanly.

attribute :eman, String, default: lazy {|r| r.name.reverse }

The part that was missing for me was the |r| parameter to the lazy block.

https://docs.chef.io/resource_common.html#lazy-evaluation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!