Chef 简明教程

Chef - Plain Ruby with Chef DSL

在 Chef 中,如果需要创建简单配方,可以使用 Chef 中可用的资源,如模板、remote_file 和服务。然而,随着配方的复杂性增加,需要使用高级技术,如条件语句,根据条件执行配方的部分内容。这是将纯 Ruby 与 Chef 特定领域语言 (DSL) 混合的优势。

In Chef, if one needs to create simple recipes one can use resources available in Chef, such as templates, remote_file, and services. However as the recipes become elaborate, one needs advanced techniques, such as conditional statements to execute parts of the recipe on condition. This is the power of mixing plain Ruby with Chef Domain Specific Language (DSL).

How to Use It?

在客户端模式下在任何节点上启动 Chef Shell,以便能够访问 Chef 服务器。

Start Chef Shell on any of the node in the client mode to be able to access the Chef server.

user@server:~$ sudo chef-shell --client
loading configuration: /etc/chef/client.rb
Session type: client
...TRUNCATED OUTPUT...
run `help' for help, `exit' or ^D to quit.
Ohai2u user@server!
Chef>

Basic Conditions with Chef DSL

使用纯 Ruby 按名称对节点进行排序。

Sort nodes by name using plain Ruby.

chef > nodes.sort! {|a,b| a.name <=> b.name }
=> [node[alice],node[server]]

遍历节点,打印其操作系统。

Loop through the nodes, printing their operating system.

chef > nodes.each do |n|
   chef > puts n['os']
   chef ?>
end
linux
windows
=> [node[server], node[alice]]

使用数组、循环和字符串扩展安装多个 Ruby gem,以构建 gem 名称。

Install multiple Ruby gems using an array, a loop, and string expansion to construct the gem names.

chef > %w{ec2 essentials}.each do |gem|
   chef > gem_package "knife-#{gem}"
   chef ?> end   => ["ec2", "essentials"]

Working Method

Chef 配方是 Ruby 文件,在 Chef 运行的环境中进行评估。它们可以包含纯 Ruby 代码(如 if 语句和循环)以及 Chef DSL 元素(如资源)。

Chef recipes are Ruby files, which gets evaluated in the context of Chef run. They can contain plain Ruby code such as if statement and loops as well as Chef DSL elements such as resources.

在配方中,可以简单地声明 Ruby 变量并将其赋予值。

Inside the recipe, one can simply declare Ruby variables and assign values to it.