Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Resources and Recipes

Ruby in Recipes - Loops, Conditions and ruby_block

Use Ruby inside Chef recipes the right way: loops that create resources, platform helpers, data-driven recipes, ruby_block, lazy values and the compile-time trap.

Because recipes are Ruby, you can use loops, conditions, methods and data structures to generate resources. That is a big advantage over configuration languages that offer only static lists. The same power creates a trap: ordinary Ruby runs at compile time while resources run at converge time. This lesson shows the idioms that make recipes short and data-driven, and the tools (ruby_block, lazy, guards) to run logic at the right moment.

Loops that create resources

When you need several similar resources, loop over a list or hash. Real recipe, read-only:

Ruby
%w(git curl vim htop).each do |pkg|
  package pkg
end

{ 'deploy' => '/home/deploy', 'backup' => '/var/backups' }.each do |name, home|
  user name do
    home home
    manage_home true
  end
end

Each iteration adds one resource to the collection. The resource names differ (package[git], package[curl], ...), which matters: two resources with the same type and name are treated as a clash ("resource cloning" warnings in older versions), so make sure names are unique.

Data-driven recipes

Put the data in attributes and let the recipe loop over it. Then changing the data never needs a code change:

Ruby
node['app']['sites'].each do |name, opts|
  directory "/var/www/#{name}" do
    owner 'www-data'
    recursive true
  end

  template "/etc/nginx/sites-available/#{name}" do
    source 'site.conf.erb'
    variables(port: opts['port'], domain: opts['domain'])
    notifies :reload, 'service[nginx]'
  end
end

Adding a site means adding a hash entry in a role or environment, not editing the recipe. The stand-in below builds such a resource list from a hash.

Ruby Stand-in: data in, resources out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Conditions and platform helpers

Chef gives you helper methods so you rarely compare strings by hand:

Ruby
if platform_family?('debian')
  package 'apache2'
elsif platform_family?('rhel')
  package 'httpd'
end

package 'lsb-release' if platform?('ubuntu')
package 'xz-utils' unless platform_family?('rhel')

Others include platform?('ubuntu', 'debian'), windows?, systemd?, docker? and version comparison through node['platform_version'].to_f. Prefer a small lookup table over long if chains:

Ruby
apache = value_for_platform_family(
  'debian' => 'apache2',
  'rhel'   => 'httpd',
  'default' => 'apache'
)
package apache

The next stand-in models value_for_platform_family.

Ruby Stand-in: a value_for_platform_family helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The compile-time trap again

Plain Ruby runs during compile, so it cannot depend on what a resource will do later. This fails on a fresh node (read-only):

Ruby
package 'git'

version = shell_out('git --version').stdout   # runs at compile time, git not installed yet

Two fixes: run the Ruby at converge time with a ruby_block, or use lazy:

Ruby
ruby_block 'record git version' do
  block do
    node.run_state['git_version'] = shell_out('git --version').stdout.strip
  end
end

file '/etc/git-version' do
  content lazy { node.run_state['git_version'] }
end

node.run_state is a hash that lives for one run, perfect for passing values between resources. (shell_out is available inside ruby_block and custom resources.)

Stand-in: run_state and lazy

The stand-in imitates ruby_block, run_state and lazy so you can see the order of events.

Ruby Stand-in: ruby_block, run_state and lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The file's content is a lambda (Chef's lazy does this), evaluated only when the file converges, after the block set the value.

Writing your own helper methods

If you repeat logic, put it in a method. Small helpers can go in a recipe, but shared ones belong in a library file (libraries/helpers.rb) of the cookbook, which Chef loads before recipes. Libraries and custom resources are covered in Cookbook Structure and Custom Resources.

Avoid doing heavy or risky work in the recipe body: network calls, reading remote files or restarting services. It runs on every compile, even when no resource needs it, and a failure there stops the whole run before any resource is applied.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a loop around package pkg produce?

    Each iteration declares a separate resource.
  2. 2. Why does shell_out('git --version') in the recipe body fail on a fresh node?

    Plain Ruby executes during compile. Put it in a ruby_block to run at converge time.
  3. 3. What is node.run_state for?

    run_state is a per-run hash that is not saved to the server.
  4. 4. Which helper returns different values by platform family without if/elsif chains?

    It looks up a value from a table keyed by family with an optional default.

Summary

  • Loops and data structures generate resources; keep the data in attributes.
  • Use helpers like platform_family? and value_for_platform_family.
  • Plain Ruby runs at compile time; use ruby_block, lazy, guards and run_state for converge-time logic.
  • Shared helper code belongs in libraries or custom resources.

Next: Cookbook Structure