在chef自定义资源中,如何指定键值对是必需的

时间:2016-02-11 12:20:30

标签: chef lwrp

在chef中编写自定义资源时,我们定义属性,类型,默认值以及是否必须指定它们,例如

attribute :plugin,        kind_of: String, required: true
attribute :after_plugin,  kind_of: String, required: false, :default => 'pam_unix.so'

假设我需要一个像Hash一样的属性

attribute :after,    kind_of: Hash, required: false, :default => {:search_interface => nil, :search_control => nil, :search_plugin => nil}

这里我提到required: false,这意味着用户不必强制提供哈希。

我需要指定如果给出Hash,那么:search_interface是强制性的

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

定义属性(现在命名属性)时,可以定义验证用户输入的回调。

有关示例,请参阅https://github.com/chef/chef/blob/cb4ee84e418164e8d2e85147efad711a42ff2799/lib/chef/resource/chef_gem.rb#L28

在你的情况下,你可以写:

attribute :after,  kind_of: Hash, required: false, 
  :default => {:search_interface => nil, :search_control => nil, :search_plugin => nil},
  :callbacks => {
    "Must contain search interface" => proc { |v| 
      v.has_key?(:search_interface)
    }
  }
}
相关问题