Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.
Step 1 − Create a helper method in cookbook’s library.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb class Chef::Recipe def netmask(ipaddress) IPAddress(ipaddress).netmask end end
Step 2 − Use the helper method.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb ip = '10.10.0.0/24' mask = netmask(ip) # here we use the library method Chef::Log.info("Netmask of #{ip}: #{mask}")
Step 3 − Upload the modified cookbook to the Chef Server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook Uploading my_cookbook [0.1.0]
user@server $ sudo chef-client ...TRUNCATED OUTPUT... [2013-01-18T14:38:26+00:00] INFO: Netmask of 10.10.0.0/24: 255.255.255.0 ...TRUNCATED OUTPUT...
Chef library code can open the chef::Recipe class and add new methods as done in Step 1. This step is not the cleanest but the simplest way of doing it.
class Chef::Recipe def netmask(ipaddress) ... end end
Once we open the chef::recipe class, there are changes that it gets polluted. As a best practice, it is always a better way to introduce a new sub class inside the library and define a method as class method. This avoids pulling the chef::recipe namespace.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb class Chef::Recipe::IPAddress def self.netmask(ipaddress) IPAddress(ipaddress).netmask end end
We can use the method inside the recipe like
IPAddress.netmask(ip)