Chef 简明教程
Chef - Libraries
Chef 中的库提供了一个可以封装已编译逻辑的位置,以便代码整洁美观。
Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.
Creating the Library
Step 1 − 在代码的库中创建帮助方法。
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 − 使用帮助方法。
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 − 将修改后的代码提交到 Chef 服务器。
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-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 库代码可以打开 chef::Recipe 类,并添加新方法(如步骤 1 中所示)。这不是最干净的步骤,但这是最简单的方法。
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
一旦我们打开 chef::recipe 类,就有可能污染该类。最佳做法是,通常最好在库中引入一个新的子类,并定义一个类方法作为方法。这样可以避免拉取 chef::recipe 命名空间。
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)