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.