Chef - Ruby Gems with Recipes


Advertisements


Recipes are the key building blocks of cookbook which is basically Ruby code. It is possible to use all of the Ruby language features inside the Chef recipe. Most of the time Ruby build in functionality is enough but sometimes one might need to use additional Ruby gems. For example, if one needs to access MySQL database from the recipe itself.

Chef recipe has the capability to get the required Ruby gems in order to use them inside the very same recipe.

Using iptable Gem in the Given Recipe

Step 1 − Edit the default recipe of the cookbook and install the gem to be used inside the recipe.

vipin@laptop:~/chef-repo $ subl 
cookbooks/my_cookbook/recipes/default.rb 
chef_gem 'ipaddress' 
require 'ipaddress' 
ip = IPAddress("192.168.0.1/24") 
Chef::Log.info("Netmask of #{ip}: #{ip.netmask}")

Step 2 − Upload the modified cookbook to the Chef server.

vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook 
Uploading my_cookbook [0.1.0] 

Step 3 − Running Chef client to see the output.

user@server $ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-01-18T14:02:02+00:00] INFO: Netmask of 192.168.0.1: 
255.255.255.0 
...TRUNCATED OUTPUT...

Working Method

Chef run steps consist of the compilation phase, where it compiles all the resources and an execution phase where Chef runs the resource providers to converge the node to the desired state. If one needs any particular Ruby gem inside the cookbook, one needs to install the gem during the complication phase.

The chef_gem resource will exactly do the same, and in Chef, Omnibus is the only way to work. Its main function is to make gems available to Chef itself.



Advertisements
E-Books Store