Chef - 库

Chef 中的库提供了一个封装编译逻辑的地方,这样菜谱中的菜谱就保持整洁干净。

创建库

步骤 1 − 在菜谱库中创建一个辅助方法。

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

步骤 2 − 使用辅助方法。

vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb
ip = '10.10.0.0/24'
mask = netmask(ip) # 这里我们使用库方法
Chef::Log.info("Netmask of #{ip}: #{mask}")

步骤 3 −将修改后的Cookbook(食谱)上传到 Chef 服务器。

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 库代码可以打开 chef::Recipe 类并添加新方法,如步骤 1 中所述。此步骤不是最干净的,但最简单的方法。

class Chef::Recipe 
def netmask(ipaddress) 
... 
end 
end

最佳实践

一旦我们打开 chef::recipe 类,就会发生污染变化。作为最佳实践,在库中引入新的子类并将方法定义为类方法始终是一种更好的方法。这避免了拉出 chef::recipe 命名空间。

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

我们可以在Kitchen(配方)中使用该方法,如下所示

IPAddress.netmask(ip)