MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Chef Tutorials: Create multiple resources in Chef recipe

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-apply and chef-client.
  • Root or sudo access, because creating users, groups and files under / and installing packages need root.
  • A configured package repository. Package names such as httpd and mysql are specific to the distribution (see the table below).
  • Outbound HTTPS access if you use the remote_file example.

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.

PurposeRHEL / CentOS / Amazon LinuxDebian / Ubuntu
Apache web serverhttpdapache2
MySQL-compatible clientmariadb (or mysql where a MySQL repo or module is enabled)mariadb-client or default-mysql-client
Directory tree viewertreetree

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 true creates /home/<user>. Without it, the user can be created without a home directory, depending on the platform defaults.
  • group with members and append true during :create adds 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.
  • checksum on remote_file takes 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' end after the remote_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

SymptomCauseFix
No candidate version available for mysql or httpdThe package name doesn't exist in the node's repositoriesUse 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 groupUse :create with members and append true, or make sure the create runs first
Group membership fails for a userThe user resource is declared after the group, or the name is misspelledDeclare users before the group and reuse the same array variable for both
remote_file fails with a 404 or a checksum mismatchThe URL is outdated or wrong, or the checksum doesn't match the fileGet the current URL and SHA-256 from the vendor download page
Permission denied or useradd errorsThe recipe was run without rootRun chef-apply or chef-client with sudo
The run stops at a license promptThe Chef license wasn't acceptedAdd --chef-license accept

Best practices

  • Use descriptive block variables (pkg, user_name, dir) instead of p. p also shadows Ruby's built-in p method.
  • Don't create test files and directories directly under /. Use a dedicated path such as /opt/<app>.
  • Always set owner, group and mode on files and directories so permissions are predictable.
  • Use the array form of package for 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-run first 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Chef Tutorials: Common Resource Functionality in chef Cookbook recipe

Common resource properties are settings that every Chef Infra resource accepts, whatever the resource type: action, ignore_failure, retries, retry_delay, sensitive, guards such as not_if and only_if, and…

Read More

Chef Tutorials: How to looping and iterative in Chef Cookbook recipe?

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…

Read More

Chef Tutorials: How to set Conditions in Chef Cookbooks recipe using Guard?

Chef guards are the not_if and only_if properties, which decide during the converge phase whether a resource runs. A guard can be a shell command string or…

Read More

Chef Tutorials: template Resource with example

The Chef template resource renders an Embedded Ruby (ERB) file from a cookbook's templates/ directory and writes the result to a path on the node. This page…

Read More

Chef Tutorials: How to set environment variable in Chef recipe

How you set an environment variable in a Chef recipe depends on who needs to see it. It might be the running chef-client process, a single execute…

Read More

Chef Tutorials: How to write and test a chef recipe?

The quickest way to write and test a Chef recipe is to put Chef resources in a single Ruby file and run it with chef-apply, which ships…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x