English 中文(简体)
Chef - Cross-Platform Cookbooks
  • 时间:2024-12-22

Chef - Cross-Platform for Cookbooks


Previous Page Next Page  

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 pst 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 
Log.info("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 cpent on the node.

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

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.

Log.info("Running on a debian derivative") if 
platform_family?( debian )

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

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

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.

node[ platform ] 

Or, you can use method style syntax −

node.platform 

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 
end 

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

Advertisements