Chef recipes are Ruby, so you loop with ordinary Ruby iterators such as each, and each pass declares one Chef resource. This page explains how the loop examples above work, fixes the ones that won't run as written, and adds patterns for looping over hashes, multi-package installs and custom resources.
How a loop works in a Chef recipe
A recipe is a Ruby file that Chef Infra Client evaluates in two phases. In the compile phase Chef runs the Ruby code from top to bottom and adds each resource it finds to the resource collection. In the converge phase it runs those resources in order. A Ruby loop runs during the compile phase, so a loop over three items adds three separate resources to the collection.
This has two consequences. First, every resource a loop creates needs a unique name, which usually comes from the item itself, for example package pkg or directory path. Second, the loop can only use data that already exists at compile time, such as node attributes, data bag items or literal arrays. If a value is only produced during the converge phase, for example by a command an earlier resource runs, use lazy { } on the property or move that logic into a custom resource.
Note: In the first two examples above, the block variable is named package, the same as the resource. Ruby still treats package package do as a method call, so the code runs, but it is hard to read. Name the variable pkg.
Corrected versions of the examples
Examples 1, 2 and 6 run as written. Examples 3, 4 and 5 will not run correctly if you paste them straight into a recipe. The table lists the problems, and the code after it is a working version of examples 3 and 5.
| Example | Problem | Fix |
|---|---|---|
| 1, 2 | The block variable package has the same name as the resource. Also, on RHEL 8 and later, the ntp package has been replaced by chrony. | Rename the variable to pkg. Use chrony on newer Red Hat family systems. |
| 3 | The default[...] lines are attribute syntax. They belong in attributes/default.rb, and inside a recipe they raise an undefined method error. | Move them to the attributes file. |
| 3 | mode 755 is a decimal integer, so Chef applies the wrong permission bits. | Use the string '0755' (or the octal integer 0755). |
| 4 | django is never defined. Also, include_recipe loads a given recipe only once per Chef run, so the loop does not run the included recipes once per site. | Use a custom resource and call it once per item (shown below). |
| 5, 6 | utilities_directory and files_directory are never defined. Building the path with a hard-coded backslash only works on Windows. | Define the variables and build paths with ::File.join. |
# attributes/default.rb
default['createdir']['shared_dir'] = 'shared-lib'
default['createdir']['config_dir'] = 'shared-config'
default['createdir']['mode'] = '0755'
default['createdir']['owner'] = 'ec2-user' # must already exist on the node
default['createdir']['group'] = 'root'Code language: PHP (php)
# recipes/default.rb
cfg = node['createdir']
["/opt/#{cfg['shared_dir']}", "/opt/#{cfg['config_dir']}"].each do |path|
directory path do
owner cfg['owner']
group cfg['group']
mode cfg['mode']
recursive true
action :create
end
end
# Example 5/6 with the variables defined and portable paths
utilities_directory = 'C:/utilities' # or '/opt/utilities' on Linux
directory utilities_directory do
recursive true
end
%w(fileX.xml fileY.xml fileZ.xml).each do |this_file|
cookbook_file ::File.join(utilities_directory, this_file) do
source this_file # looked up under the cookbook's files/ directory
action :create
end
endCode language: PHP (php)
source in cookbook_file is resolved relative to the cookbook's files/ directory, so source this_file finds files/fileX.xml. Chef on Windows accepts forward slashes in paths, so ::File.join works on both platforms. The leading :: makes sure Ruby uses the core File class and not Chef's file resource.
Looping over hashes and node attributes
Real cookbooks usually loop over data held in attributes rather than over literal arrays. That lets roles, environments or Policyfiles change the list without editing the recipe. When you call each on a hash, it passes a key and a value to the block.
# attributes/default.rb
default['app']['users'] = {
'deploy' => { 'uid' => 2001, 'shell' => '/bin/bash' },
'backup' => { 'uid' => 2002, 'shell' => '/sbin/nologin' },
}Code language: PHP (php)
# recipes/users.rb
node['app']['users'].each do |name, props|
user name do
uid props['uid']
shell props['shell']
manage_home true
action :create
end
end
# each_with_index when you need a counter
%w(web1 web2 web3).each_with_index do |site, i|
directory "/srv/#{site}" do
mode '0755'
end
file "/srv/#{site}/port" do
content "#{8080 + i}\n"
end
endCode language: PHP (php)
Other Ruby iterators work the same way, for example 3.times { |i| ... }, select or reject to filter a list first, and sort when the order of resources matters.
Installing several packages without a loop
For packages you often don't need a loop at all. The package resource accepts an array on platforms whose package provider supports it, including apt, yum and dnf. Chef then installs every package in one package-manager call, which is faster than running a separate transaction for each package.
package %w(vim git chrony) do
action :install
endCode language: JavaScript (javascript)
Use a loop when each item needs different properties, for example a different version or its own notifications.
Replacing the include_recipe loop with a custom resource
Example 4 tries to repeat a set of recipes once per site. That doesn't work, because include_recipe ignores any recipe that is already in the run. Changing node.default inside the loop also only changes one shared attribute, so every site ends up with the last value. The supported way to repeat a group of resources with different inputs is a custom resource.
# resources/django_site.rb (cookbook name: my_app)
unified_mode true
property :site_name, String, name_property: true
property :port, Integer, default: 8000
action :create do
template "/etc/nginx/conf.d/#{new_resource.site_name}.conf" do
source 'nginx-site.conf.erb'
variables(name: new_resource.site_name, port: new_resource.port)
end
# add gunicorn / supervisor resources for the site here
endCode language: PHP (php)
# attributes/default.rb
default['my_app']['sites'] = [
{ 'name' => 'shop', 'port' => 8001 },
{ 'name' => 'blog', 'port' => 8002 },
]
# recipes/default.rb
node['my_app']['sites'].each do |site|
my_app_django_site site['name'] do
port site['port']
end
endCode language: PHP (php)
Chef names the resource after the cookbook and the file name (my_app + django_site). Each loop pass creates its own instance with its own properties, so every site is configured separately.
Running and verifying the recipe
- Lint the cookbook with
cookstyle .from the cookbook directory. It catches style problems and common mistakes, such as a numericmode. - Converge locally without a Chef Infra Server:
sudo chef-client --local-mode --runlist 'recipe[my_app]'from your chef-repo directory. - Check the output. Each loop item should appear as its own resource, for example one
directory[/opt/shared-lib]entry and onedirectory[/opt/shared-config]entry. - Run the converge again. A correct recipe reports
0/N resources updatedon the second run, which shows that it is idempotent. - Check the result on the node, for example
stat -c '%a %U' /opt/shared-libshould print755 ec2-user.
For repeatable testing on throwaway machines, run the same recipe with Test Kitchen and check the result with InSpec controls.
Common errors and best practices
undefined method 'default'in a recipe: you used attribute syntax inside a recipe. Move it toattributes/default.rb, or usenode.default[...]if you really must set it in the recipe.undefined local variable or method: a variable such asdjangoorfiles_directorywas never defined. Define it, or read it fromnode[...].- Wrong permissions such as
1363:modewas given as a decimal integer. Use quoted strings like'0644'. - Notifications hit the wrong resource: two loop passes created resources with the same name. Build the name from the loop item so each one is unique.
user does not existonowner: the owner must already exist on the node. Create it earlier in the run with auserresource.- Keep the list of items in attributes and the logic in the recipe, so you can change the list per environment without editing code.
- Avoid
ruby_blockorexecuteinside loops when a native resource exists. Native resources are idempotent and report changes properly.
Frequently asked questions
How do I loop through an array in a Chef recipe?
Call Ruby's each on the array and declare a resource inside the block, for example %w(vim git).each { |pkg| package pkg }. Chef adds one resource for each element during the compile phase.
Can I install multiple packages in Chef without a loop?
Yes. On platforms whose provider supports it, such as apt, yum and dnf, you can pass an array to package, for example package %w(vim git chrony). Chef then installs all of them in a single package-manager call.
Why does include_recipe inside a loop only run once?
Chef includes each recipe only once per run, and later include_recipe calls for the same recipe do nothing. To repeat a set of resources with different inputs, write a custom resource and call it once per item.
How do I loop over a hash of attributes in Chef?
Use node['app']['users'].each do |name, props| ... end. The block receives each key and its value, so you can use props['uid'] and similar values as resource properties.
Why is my directory created with the wrong permissions in a loop?
The mode was probably given as an unquoted decimal number such as 755. Chef reads that as decimal, not octal. Use a string such as '0755'.
Related tutorials
- More Chef tutorials
- What is Chef and use cases of Chef?
- Chef Tutorials: knife command line reference
- Top 50 Chef interview questions and answers
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals