In the previous article we learned more about Chef cookbooks. In this article we will learn what is Ohai and how to write Ohai plugin.
Ohai
Ohai detects data about your operating system. It can be used standalone, but its primary purpose is to provide node data to Chef.
When invoked, it collects detailed, extensible information about the machine it’s running on, including Chef configuration, hostname, FQDN, networking, memory, CPU, platform, and kernel data.
When Chef configures the node object during each Chef run, these attributes are used by the chef-client to ensure that certain properties remain unchanged. These properties are also referred to as automatic attributes. In our case (in Chef Solo), this attributes available in node object. For example:
Ohai plugin
In our cookbook “tomatoes” we already have node.js recipe. Let’s create ohai plugin, which will provide for us information about already installed on system node.js. We will use this information to check if we need install node.js on server.
First of all create in “tomatoes” new recipe “ohai_plugin.rb” with content:
This recipe will generate ohai plugin from template “system_node_js.rb”. Next we should create this template in folder “tomatoes/templates/default/plugins”:
In first two lines we set by method “provides” automatic attributes, which will provide for us this plugin.
Most of the information we want to lookup would be nested in some way, and ohai tends to do this by storing the data in a Mash. This can be done by creating a new mash and setting the attribute to it. We did this with “system_node_js”.
In the end of code, plugin set the version of node.js, if node.js installed on server. That’s it!
Next, let’s try this plugin by adding “default.rb” recipe this content:
Now test it by running the command “vagrant provision”. When you first start, you will not see anything, as the plugin will be delivered later chef-client launched. But the second time, you should see a similar picture in the log:
In this case we can little change our node.js recipe:
Let’s try to change node.js version in role “web.json”:
And restart “vagrant provision”:
And after some time, the server will have a new node.js:
And on next launch of chef solo you should see new version of node.js:
Summary
In the current article we have learn Ohai and how to write Ohai plugin.