Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.
Creating the Library
Step1 − 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
Step2 − 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}")
Step3 − Upload the modified cookbook to the Chef Server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook Uploading my_cookbook [0.1.0]
Testing the Library
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...
Working Method
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
Best Practices
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)