English 中文(简体)
Chef - Libraries
  • 时间:2024-11-05

Chef - Libraries


Previous Page Next Page  

Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.

Creating the Library

Step 1 − Create a helper method in cookbook’s pbrary.

vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/pbraries/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 pbrary 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] 

Testing the Library

user@server $ sudo chef-cpent 
...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 pbrary 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 pbrary and define a method as class method. This avoids pulpng the chef::recipe namespace.

vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/pbraries/ipaddress.rb 
class Chef::Recipe::IPAddress 
def self.netmask(ipaddress) 
IPAddress(ipaddress).netmask 
end 
end 

We can use the method inside the recipe pke

IPAddress.netmask(ip) 
Advertisements