what ruby features are used in chef recipes?

柔情痞子 提交于 2020-02-25 16:52:27

问题


I just started using chef and don't know much about ruby.

I have problems understanding the language-syntax used in recipes.

Say, I create a directory in a cookbook in recipes/default.rb like:

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

I assume this is part of a valid ruby script. What do lines like owner "test" mean? Is this a function call, a variable assignment or something else entirely?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/20569521/what-ruby-features-are-used-in-chef-recipes

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