Chef - 測試 Cookbook



如果 Cookbook 直接部署並執行在生產伺服器上,Cookbook 在生產環境中崩潰的可能性很高。防止這種情況發生的最佳方法是在設定環境中測試 Cookbook。

以下是測試步驟。

步驟 1 - 使用以下命令安裝 Cookbook。

vipin@laptop:~/chef-repo $ knife cookbook site install <cookbook name> 

步驟 2 - 在可工作的 Cookbook 上執行 knife cookbook test 命令。

vipin@laptop:~/chef-repo $ knife cookbook test VTest  
checking ntp 
Running syntax check on ntp 
Validating ruby files 
Validating templates

步驟 3 - 破壞 Cookbook 中的內容,然後再次測試。

vipin@laptop:~/chef-repo $ subl cookbooks/VTest/recipes/default.rb 
... 
[ node['ntp']['varlibdir'] 
node['ntp']['statsdir'] ].each do |ntpdir| 
   directory ntpdir do 
      owner node['ntp']['var_owner'] 
      group node['ntp']['var_group'] 
      mode 0755 
   end 
end

步驟 4 - 再次執行 knife test 命令。

vipin@laptop:~/chef-repo $ knife cookbook test ntp 
checking ntp 
Running syntax check on ntp 
Validating ruby files 
FATAL: Cookbook file recipes/default.rb has a ruby syntax error: 
FATAL: cookbooks/ntp/recipes/default.rb:25: syntax error, 
unexpected tIDENTIFIER, expecting ']' 
FATAL: node['ntp']['statsdir'] ].each do |ntpdir| 
FATAL: ^ 
FATAL: cookbooks/ntp/recipes/default.rb:25: syntax error, 
unexpected ']', expecting $end 
FATAL: node['ntp']['statsdir'] ].each do |ntpdir| 
FATAL: 

工作方法

Knife cookbook test 會對 Cookbook 中的所有 Ruby 檔案以及所有 ERB 模板執行 Ruby 語法檢查。它迴圈遍歷 Ruby 檔案,並對每個檔案執行 Ruby –c。Ruby –c 檢查指令碼的語法,並在不執行指令碼的情況下退出。

遍歷所有 Ruby 檔案後,knife cookbook test 會遍歷所有 ERB 模板,並將 –x 建立的冗餘版本透過管道傳遞給 Ruby –c

侷限性

Knife cookbook test 只對 Ruby 檔案和 ERB 模板進行簡單的語法檢查。我們可以使用 ChefSpec 和 Test Kitchen 進行完全測試驅動。

廣告
© . All rights reserved.