what ruby features are used in chef recipes?

社会主义新天地 提交于 2019-12-02 02:50:55

Chef is written in Ruby and makes an extensive use of Ruby ability to design custom DSL. Almost every chef configuration file is written with a Ruby-based DSL.

This means that in order to use chef effectively you should be familiar with the basic of Ruby syntax including

  • Grammar
  • Data types (the main difference compared to other languages are Symbols)
  • Blocks

You don't need to know a lot about metaprogramming in Ruby.

The case of the code you posted is an excellent example of a Ruby based DSL. Let me explain it a little bit.

# 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

Blocks are a convenient way to specify a group of operations (in this case create, set permissions, etc) to be evaluated in a single context (in this case in the context of that path).

Let's break it down.

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

You are just calling a global method defined by Chef called directory, passing one argument "/home/test/mydir", and a block (everything between the do and end).

This block is probably excecuted in a special scope created by Chef in which all of the options (owner, mode, action, etc.) are method.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!