Chef 简明教程
Chef - Ruby Gems with Recipes
配方是 cookbook 的关键构建模块,它基本上是 Ruby 代码。可以在 Chef 配方中使用 Ruby 语言的所有功能。大多数情况下,Ruby 的内置功能已经足够,但在某些情况下,可能需要使用其他 Ruby gem。例如,如果需要从配方本身访问 MySQL 数据库。
Recipes are the key building blocks of cookbook which is basically Ruby code. It is possible to use all of the Ruby language features inside the Chef recipe. Most of the time Ruby build in functionality is enough but sometimes one might need to use additional Ruby gems. For example, if one needs to access MySQL database from the recipe itself.
Chef 配方有能力获取所需的 Ruby gem,以便在同一个配方中使用它们。
Chef recipe has the capability to get the required Ruby gems in order to use them inside the very same recipe.
Using iptable Gem in the Given Recipe
Step 1 − 编辑 cookbook 的默认配方,并安装将在配方中使用的 gem。
Step 1 − Edit the default recipe of the cookbook and install the gem to be used inside the recipe.
vipin@laptop:~/chef-repo $ subl
cookbooks/my_cookbook/recipes/default.rb
chef_gem 'ipaddress'
require 'ipaddress'
ip = IPAddress("192.168.0.1/24")
Chef::Log.info("Netmask of #{ip}: #{ip.netmask}")
Step 2 − 将修改后的代码提交到 Chef 服务器。
Step 2 − Upload the modified cookbook to the Chef server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook
Uploading my_cookbook [0.1.0]
Step 3 − 运行 Chef 客户端查看输出。
Step 3 − Running Chef client to see the output.
user@server $ sudo chef-client
...TRUNCATED OUTPUT...
[2013-01-18T14:02:02+00:00] INFO: Netmask of 192.168.0.1:
255.255.255.0
...TRUNCATED OUTPUT...
Working Method
Chef 运行步骤包括编译阶段(编译所有资源)和执行阶段(Chef 运行资源提供程序使节点进入所需状态)。如果在代码中需要任何特定的 Ruby gem,则需要在复杂阶段安装该 gem。
Chef run steps consist of the compilation phase, where it compiles all the resources and an execution phase where Chef runs the resource providers to converge the node to the desired state. If one needs any particular Ruby gem inside the cookbook, one needs to install the gem during the complication phase.
chef_gem 资源将执行完全相同的功能,并且在 Chef 中,Omnibus 是唯一的工作方式。它的主要功能是对 Chef 本身提供 gem。
The chef_gem resource will exactly do the same, and in Chef, Omnibus is the only way to work. Its main function is to make gems available to Chef itself.