A Chef recipe is Ruby, so you can create many resources of the same type by looping over an array with .each and declaring one resource per item, as the example recipe above does for packages, users, files, directories and groups. This page explains how that pattern works, how to run and check the recipe, and how to tighten it for real servers.
How the loop pattern works
%w(tree mysql httpd) is Ruby shorthand for the array ['tree', 'mysql', 'httpd']. Calling .each on it runs the block once per element. Inside the block, package p do ... end declares a separate resource for each value. Chef compiles all of these into the resource collection before it changes anything, then runs them in the order they were declared.
Ruby builds the resources at compile time. Chef applies them at converge time. Each loop iteration produces an ordinary resource such as package[tree] or user[Ramesh], which appears in the run output and can be notified by name like any other resource.
Note: Keep resource names unique. If two iterations produce the same type and name, for example file[/ktfile1] twice, you get two resources that act on the same target, and the later one can undo the earlier one.
Prerequisites
- A Linux node with Chef Infra Client or Chef Workstation installed. Workstation includes
chef-applyandchef-client. - Root or
sudoaccess, because creating users, groups and files under/and installing packages need root. - A configured package repository. Package names such as
httpdandmysqlare specific to the distribution (see the table below). - Outbound HTTPS access if you use the
remote_fileexample.
Run the recipe and verify the result
Save the example above as chef.rb. You can run a single recipe file without a cookbook or a Chef Server:
# Run a standalone recipe file
sudo chef-apply chef.rb --chef-license accept
# Alternative: local mode, with a dry run first
sudo chef-client --local-mode --why-run chef.rb --chef-license accept
sudo chef-client --local-mode chef.rb --chef-license acceptCode language: PHP (php)
The output lists each resource the loops generated, for example * yum_package[tree] action install followed by - install version ... of package tree. When you run it a second time, the same resources report (up to date). That confirms the recipe is idempotent.
rpm -q tree httpd # or: dpkg -l tree apache2 on Debian/Ubuntu
id Ramesh; id Ajay; id Vinod
getent group ktexperts1 # members should list Ramesh,Ajay,Vinod
ls -l /ktfile1 /ktfile2 /ktfile3
ls -ld /ktdir1 /ktdir2 /ktdir3
ls -l /home/ec2-user/*.rpmCode language: PHP (php)
Package names differ by platform
The package resource calls the platform's native provider (yum/dnf, apt, and others). It does not translate package names, so httpd and mysql only work where packages with those exact names exist.
| Purpose | RHEL / CentOS / Amazon Linux | Debian / Ubuntu |
|---|---|---|
| Apache web server | httpd | apache2 |
| MySQL-compatible client | mariadb (or mysql where a MySQL repo or module is enabled) | mariadb-client or default-mysql-client |
| Directory tree viewer | tree | tree |
If a name doesn't exist, the run stops with an error saying no candidate version is available. To fix it, pick the correct name per platform with node['platform_family'], as the improved recipe below does.
Improved version of the recipe
The recipe below follows the same steps as the example above with these changes: packages install in one transaction, usernames are lowercase, home directories are created, the group is created with its members in one resource, files have content and permissions, and the download is pinned with a checksum.
# chef.rb - create multiple resources with loops
# 1. Packages: the package resource accepts an array (one yum/dnf/apt call)
db_client = node['platform_family'] == 'debian' ? 'mariadb-client' : 'mariadb'
web = node['platform_family'] == 'debian' ? 'apache2' : 'httpd'
package ['tree', web, db_client] do
action :install
end
# 2. Users: lowercase names, home directories created
team = %w(ramesh ajay vinod)
team.each do |u|
user u do
shell '/bin/bash'
manage_home true
action :create
end
end
# 3. Groups: the first group gets the team as members
%w(ktexperts1 ktexperts2 ktexperts3).each do |grp|
group grp do
members team if grp == 'ktexperts1'
append true
action :create
end
end
# 4. Directories under a dedicated base path, not /
base = '/opt/ktdemo'
directory base do
mode '0755'
end
%w(dir1 dir2 dir3).each do |d|
directory "#{base}/#{d}" do
owner 'root'
group 'ktexperts1'
mode '0775'
action :create
end
end
# 5. Files with managed content and permissions
%w(file1 file2 file3).each do |f|
file "#{base}/#{f}" do
content "Managed by Chef - #{f}\n"
owner 'root'
group 'ktexperts1'
mode '0644'
action :create
end
end
# 6. Download a file, verified by checksum
pkg_url = 'https://example-mirror.internal/chef-workstation.rpm' # replace with a real URL
pkg_sha256 = 'REPLACE_WITH_SHA256' # from the download page
remote_file '/tmp/chef-workstation.rpm' do
source pkg_url
checksum pkg_sha256
mode '0644'
action :create
endCode language: PHP (php)
package [...]with an array installs all packages in one package-manager call. This is faster and atomic. It replaces the loop where the provider supports multi-package installs (yum, dnf and apt do).manage_home truecreates/home/<user>. Without it, the user can be created without a home directory, depending on the platform defaults.groupwithmembersandappend trueduring:createadds the users without removing any existing members. Because the users are declared earlier in the recipe, they exist by the time the group resource runs.checksumonremote_filetakes a SHA-256. If the local file already matches it, Chef skips the download. If the downloaded content doesn't match, the run fails, so a corrupted or tampered file never reaches the node.- To install the downloaded RPM, add
package 'chef-workstation' do source '/tmp/chef-workstation.rpm' endafter theremote_file.
Loop over a hash when items need different properties
An array works when every resource is identical except for its name. When each item needs its own settings, loop over a hash instead:
app_users = {
'ramesh' => { uid: 2001, shell: '/bin/bash' },
'ajay' => { uid: 2002, shell: '/bin/bash' },
'vinod' => { uid: 2003, shell: '/sbin/nologin' },
}
app_users.each do |name, opts|
user name do
uid opts[:uid]
shell opts[:shell]
manage_home true
end
endCode language: PHP (php)
In a cookbook, move this data into attributes (for example node['ktdemo']['users']) or a data bag. That way you can change the list per environment without editing the recipe.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
No candidate version available for mysql or httpd | The package name doesn't exist in the node's repositories | Use the platform-specific name (see the table above) or enable the repository first |
group[ktexperts1] with :modify fails because the group doesn't exist | :modify only changes an existing group | Use :create with members and append true, or make sure the create runs first |
| Group membership fails for a user | The user resource is declared after the group, or the name is misspelled | Declare users before the group and reuse the same array variable for both |
remote_file fails with a 404 or a checksum mismatch | The URL is outdated or wrong, or the checksum doesn't match the file | Get the current URL and SHA-256 from the vendor download page |
| Permission denied or useradd errors | The recipe was run without root | Run chef-apply or chef-client with sudo |
| The run stops at a license prompt | The Chef license wasn't accepted | Add --chef-license accept |
Best practices
- Use descriptive block variables (
pkg,user_name,dir) instead ofp.palso shadows Ruby's built-inpmethod. - Don't create test files and directories directly under
/. Use a dedicated path such as/opt/<app>. - Always set
owner,groupandmodeon files and directories so permissions are predictable. - Use the array form of
packagefor bulk installs instead of a loop. - Pin downloads with
checksum, and keep URLs and versions in attributes rather than hard-coding them. - Run with
--why-runfirst on shared servers to preview the changes.
Frequently asked questions
How do I install multiple packages in a single Chef resource?
Pass an array to the package resource, for example package %w(tree httpd git). On yum, dnf and apt platforms, Chef installs them in one package-manager transaction.
What does %w() mean in a Chef recipe?
It's Ruby syntax for an array of strings separated by whitespace. %w(a b c) is the same as ['a', 'b', 'c'], and you can call .each on it to declare one resource per element.
Does looping over resources break idempotency?
No. Each iteration creates a normal Chef resource that checks the current state before acting. On a second run, every resource reports up to date unless something has changed.
How do I add several users to a group without removing existing members?
Set members to an array of usernames and add append true on the group resource. Without append true, Chef replaces the group's member list with exactly the users you listed.
How can I run a single recipe file without a cookbook?
Use sudo chef-apply recipe.rb or sudo chef-client --local-mode recipe.rb. Both run the file directly on the local node without a Chef Infra Server.
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