Chef - Cross-Platform for Cookbooks


Cross-Platform cookbooks are those cookbooks which adopt an underlying environment on which it is going to run. Chef provides a host of features, which helps in writing crossplatform cookbooks capable of running on any OS, on which it is going to get deployed. This helps a developer to write a completely operational cookbook.

In order to do this, we need to have a cookbook. In our case it will be test_cookbook and a run list which will have the cookbook definition in it.

Working Method

Retrieving the nodes platform detail and executing the conditional logic in our cookbook depends on the platform. In our case, we will test it for Ubuntu.

Step 1 − Log a message if the node is Ubuntu.

vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb"Running on ubuntu") if node.platform['ubuntu'] 

Step 2 − Upload the cookbook to Chef server.

vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb 
Uploading my_cookbook [0.1.0] 
Uploaded 1 cookbook. 

Step 3 − Run the Chef client on the node.

user@server:~$ sudo chef-client 
[2013-03-03T20:07:39+00:00] INFO: Running on Ubuntu 

Alternatively, if one is not interested in a specific platform but only needs to know which declarative one is using, the following statement can be used."Running on a debian derivative") if 

Uploading the modified cookbook and running Chef client on Ubuntu node will show the following result.

[2013-03-03T20:16:14+00:00] INFO: Running on a debian 

Workflow of Scripts

In the above command, Ohai will discover the current status of the node’s operating system and store it as a platform attribute with the node object.


Or, you can use method style syntax −


Setting Platform Specific Values

In order to set platform specific values chef offers convenience methods value_for_platform and value_for_platform_family. They can be used to avoid complex case statement and use a simple hash instead.

Example cookbook

execute "start-runsvdir" do 
   command value_for_platform( 
      "debian" => { "default" => "runsvdir-start" }, 
      "ubuntu" => { "default" => "start runsvdir" }, 
      "gentoo" => { "default" => "/etc/init.d/runit-start start" } 
   action :nothing 

In the above example, the command is OS specific as defined.

  • For Debian, "runsvdir-start" will work
  • For Ubuntu, "start runsvdir" will work
  • For Gentoo, "/etc/init.d/runit-start" will work