Chef (2) Chef Recipe

Chef Recipe is a ruby script which is similar to Linux Bash or Windows Batch. We can add the tasks to the recipe and Chef would handle these tasks.


1. Hello Chef World:

First, create a chef recipe which is named "hello.rb".

# hello.rb
file "hello.txt" do
  content "Hello Chef World"
end

Run "chef-apply" command to start the process.

$ chef-apply hello.rb

This recipe would create a hello.txt in the same directory and the content is "Hello Chef World".


2. Using the Environment Variable:

We can use the Environment Variable in the chef recipe.

# env_test.rb
file "#{ENV['HOME']}/env_test.txt" do
  content "Environment Variable."
end

This recipe add a file named "env_test.txt" to your home directory.

Let's append a new line to the text file and execute the recipe.

$ echo "New line" >> env_test.txt
$ chef-apply env_test.rb

Chef checks the existence of the text file at first. If the file is already exist, Chef would check the content of the text file. If the content is different to the recipe, Chef updates the content. That's why we say Chef is smarter than Bash.


3. cleanup.rb

Finally, let's remove the text file from the system.

# cleanup.rb
file #{ENV['HOME']}/env_test.txt" do
  "action :delete
end

留言

熱門文章