In chef custom resource how to specify that a key value pair is mandatory

670 views Asked by At

While writing custom resources in chef we define attributes, their type, their default value and whether they are mandatory to be specified or not, e.g.

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

Suppose I need to take an attribute that is a Hash like

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

Here I have mentioned required: false which means it is not mandatory for user to provide the Hash.

I need to specify that if the Hash is given, then the :search_interface is mandatory

How can I achieve that?

1

There are 1 answers

0
kamaradclimber On BEST ANSWER

When defining attribute (now named property), you can define callbacks that validate the user input.

See https://github.com/chef/chef/blob/cb4ee84e418164e8d2e85147efad711a42ff2799/lib/chef/resource/chef_gem.rb#L28 for an example.

In your case, you could write:

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)
    }
  }
}