【问题标题】:what ruby features are used in chef recipes?厨师食谱中使用了哪些红宝石功能?
【发布时间】:2014-01-01 09:36:05
【问题描述】:

我刚开始使用 chef,对 ruby​​ 了解不多。

我无法理解食谱中使用的语言语法。

说,我在 recipes/default.rb 的食谱中创建了一个目录,例如:

directory "/home/test/mydir" do
  owner "test"
  mode "0755"
  action :create
  recursive true
end

我认为这是一个有效的 ruby​​ 脚本的一部分。像owner "test" 这样的行是什么意思?这是一个函数调用、一个变量赋值还是其他什么?

【问题讨论】:

标签: ruby syntax chef-infra


【解决方案1】:

Chef 是用 Ruby 编写的,并广泛使用 Ruby 设计自定义 DSL 的能力。几乎每个 Chef 配置文件都是使用基于 Ruby 的 DSL 编写的。

这意味着为了有效地使用 chef,你应该熟悉基本的 Ruby 语法,包括

  • 语法
  • 数据类型(与其他语言相比的主要区别是符号)
  • 方块

您不需要对 Ruby 中的元编程了解很多。

您发布的代码案例是基于 Ruby 的 DSL 的绝佳示例。让我稍微解释一下。

# Call the method directory passing the path and a block
# containing some code to be evaluated
directory "/home/test/mydir" do

  # chown the directory to the test user
  owner "test"

  # set the permissions to 0555
  mode "0755"

  # create the directory if it does not exists
  action :create

  # equivalent of -p flag in the mkdir
  recursive true

end

块是指定一组操作(在本例中为创建、设置权限等)在单个上下文(在本例中为该路径的上下文)中评估的便捷方式。

【讨论】:

【解决方案2】:

让我们分解一下。

directory "/home/test/mydir" do
  ...
end

您只是调用了一个由 Chef 定义的名为 directory 的全局方法,传递了一个参数 "/home/test/mydir" 和一个块(doend 之间的所有内容)。

此块可能在 Chef 创建的特殊范围内执行,其中所有选项(ownermodeaction 等)都是方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多