Chef教程
Chef高级

Chef 资源库

Chef 中的库提供了一个封装编译逻辑的地方,以便Cookbook保持整洁。

创建库

步骤 1-在Cookbook库中创建一个辅助方法。
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) # here we use the library method 
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 
我们可以像这样使用配方中的方法
IPAddress.netmask(ip) 
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4