chamilad
chamilad

Reputation: 1669

Setting and Accessing Custom Ohai attributes in Chef

I set a list of attributes to ohai as follows.

Ohai.plugin(:mycustom) do
    provides "mycustom"

    collect_data do
        configs = ["sss=fdf", "tryet=werw"]
        Ohai::Log.info("Adding #{configs.length} ohai parameters..........................")
        configs.each { |param|
            if param.to_s.strip.length != 0
                key_value_pair = param.split("=").map(&:strip)
                mycustom Mash.new
                mycustom["mycustom_#{key_value_pair[0].downcase}"] = "#{key_value_pair[1]}"
            end
        }
    end
end

And I configure the run list to run ohai and then my recipe in sequence. How do I access the above set attributes in my recipe's templates?

<%= node['mycustom_sss'] %>

doesn't seem to work.

If I execute ohai | grep mycustom after the run list is run it doesn't return anything.

Upvotes: 1

Views: 3248

Answers (1)

Matt
Matt

Reputation: 74801

Your plugin provides mycustom so the new Mash and it's values will reside under node['mycustom']. Your example would result in node['mycustom']['mycustom_key']

I can see one issue where you are replacing the mycustom Mash on each iteration of the loop so you would only ever end up with the one final value, but you should still have the one.

As you already get the prefix node['mycustom'] via provide 'mycustom' you can house the attributes directly underneath that rather then building a string including mycustom for the key.

Ohai.plugin(:Mycustom) do
  provides 'mycustom'

  collect_data do

    mycustom Mash.new
    configs = [ "sss=fdf", "tryet=werw" ]
    Ohai::Log.info "Adding #{configs.length} ohai parameters......"

    extract_string_key_values(configs).each do |key,val| 
      Ohai::Log.debug "Got key [#{key}] val [#{val}]"
      next if key.length == 0
      mycustom[key.downcase] = val
    end

  end


  def extract_string_key_values array
    #  Split the array values on = and strip whitespace from all elements 
    array.map{|keyval| keyval.split('=').map(&:strip) }
  end

end

This is ohai 7 but they're not vastly different. I split out the key/val parsing into a separate method so the loop is cleaner.

For command line ohai to pick up the plugin, you need to give it a directory to look in, unless you install the plugin in the original ruby ohai gem path.

ohai -d /your/ohai/dir | grep -A3 mycustom
[2014-09-04T21:00:32+01:00] INFO: Adding 2 ohai parameters...
  "mycustom": {
    "sss": "fdf",
    "tryet": "werw"
  }

Then they would then appear like so in your node structure:

node[:mycustom][:sss] = fdf
node[:mycustom][:tryet] = "werw"

After a chef run you should be able to see the nodes mycustom attributes with knife

knife node show <nodename> -a mycustom

Upvotes: 0

Related Questions