
- Chef 教程
- Chef - 首頁
- Chef - 概述
- Chef - 架構
- Chef - 版本控制系統設定
- Chef - 工作站設定
- Chef - 客戶端設定
- Chef - Test Kitchen 設定
- Chef - Knife 設定
- Chef - Solo 設定
- Chef - Cookbook
- Chef - Cookbook 依賴關係
- Chef - 角色
- Chef - 環境
- Chef - Chef-Client 作為守護程序
- Chef - Chef-Shell
- Chef - 測試 Cookbook
- Chef - Foodcritic
- Chef - ChefSpec
- 使用 Test Kitchen 測試 Cookbook
- Chef - 節點
- Chef - Chef-Client 執行
- 高階 Chef
- 動態配置菜譜
- Chef - 模板
- Chef - Chef DSL 的純 Ruby 程式碼
- Chef - 菜譜中的 Ruby Gems
- Chef - 庫函式
- Chef - 定義
- Chef - 環境變數
- Chef - 資料包
- Chef - 資料包指令碼
- Chef - 跨平臺 Cookbook
- Chef - 資源
- 輕量級資源提供程式
- Chef - 藍圖
- Chef - 檔案和包
- Chef - 社群 Cookbook
- Chef 有用資源
- Chef - 快速指南
- 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)
廣告