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: 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 with Chef Workstation and needs no Chef Infra Server or cookbook. The steps below create a file with the file resource, then run it normally, with debug logging and in why-run mode. The sections after them complete the missing install step and show how to check idempotency, lint with Cookstyle and confirm the result with Chef InSpec.


Step 1 – Install & Verify Chef Workstation


Step 2 – Write a following content in hello.rb


file 'index.html' do
  content "Hello everyone from DevOpsSchool"
endCode language: JavaScript (javascript)

Step 3 – Write a following content in hello.rb


$ chef-apply hello.rb
$ chef-apply hello.rb
$ chef-apply hello.rb -l debug
$ chef-apply hello.rb --why-run

Run the executable in why-run mode, which is a type of Chef Infra Client run that does everything except modify the system. Use why-run mode to understand why the Chef Infra Client makes the decisions that it makes and to learn more about the current and proposed state of the system.


Corrections to the steps above

  • Step 1 has no commands. The install and verify steps are filled in in the next section.
  • Step 3 has the wrong heading. It repeats "Write a following content in hello.rb", but this step runs the recipe. A better heading is "Run the recipe with chef-apply".
  • The repeated chef-apply hello.rb line is not explained. Running the recipe a second time is a deliberate idempotency check. The second run should report the resource as (up to date) and change nothing.
  • The relative path index.html is resolved against the current working directory. The file ends up wherever you ran the command. Use an absolute path in real recipes so the result is predictable.
  • License acceptance is missing. On first use, Chef Infra tools ask you to accept the Chef license. On a non-interactive shell or in CI the run fails unless you pass --chef-license accept.

Install and verify Chef Workstation

Chef Workstation bundles Chef Infra Client (which provides chef-apply), Chef InSpec, Cookstyle, ChefSpec and Test Kitchen. Download the package for your operating system from Chef's official downloads page, then install it with the package manager for your system.

# Debian / Ubuntu
sudo dpkg -i chef-workstation_*.deb

# RHEL / Rocky / Alma / Amazon Linux
sudo rpm -Uvh chef-workstation-*.rpm

# macOS (Homebrew)
brew install --cask chef-workstationCode language: PHP (php)

Verify the install and make the embedded Ruby and tools the default in your shell:

chef -v
# Lists the versions of Chef Workstation, Chef Infra Client, Chef InSpec,
# Chef CLI, Test Kitchen and Cookstyle

which chef-apply

# Optional: use Workstation's embedded Ruby in this shell
eval "$(chef shell-init bash)"Code language: PHP (php)

Note: To accept the license once without being prompted, run chef-apply with --chef-license accept the first time, or export CHEF_LICENSE=accept in CI jobs.

What the recipe does and what to expect

file 'index.html' declares a resource: the type is file and the name is the path. The content property describes the desired state. Chef compares that desired state with what is on disk and acts only if they differ. With no action line, the default action :create is used.

The first run creates the file and prints a diff. The checksum and temp file names will differ on your machine:

$ chef-apply hello.rb
Recipe: (chef-apply cookbook)::(chef-apply recipe)
  * file[index.html] action create
    - create new file index.html
    - update content in file index.html from none to 3b1f2e
    --- index.html
    +++ ./.chef-index20261201-12345-abcd.html
    @@ -1 +1,2 @@
    +Hello everyone from DevOpsSchoolCode language: JavaScript (javascript)

The second run changes nothing. This is the idempotency check that the repeated command above is there for:

$ chef-apply hello.rb
Recipe: (chef-apply cookbook)::(chef-apply recipe)
  * file[index.html] action create (up to date)

Edit index.html by hand and run the recipe again. Chef detects the drift and restores the declared content. This convergence behaviour is the main reason to manage configuration with Chef instead of shell scripts.

A more realistic recipe

Real recipes use absolute paths, set ownership and permissions, and combine several resources. This version creates a directory and a file inside it. It writes under /tmp, so no root access is needed:

directory '/tmp/devopsschool' do
  mode '0755'
  action :create
end

file '/tmp/devopsschool/index.html' do
  content "Hello everyone from DevOpsSchool\n"
  mode '0644'
  action :create
endCode language: JavaScript (javascript)

Resources run in the order they are written, so the directory exists before the file is created. To remove the file, change the action to action :delete and run chef-apply again. Recipes that manage packages, services or files under /etc must be run with sudo.

Testing the recipe

"Testing" a recipe covers several levels. For a single-file recipe, the following steps catch most problems before anything touches a real server:

  1. Syntax check: chef exec ruby -c hello.rb should print Syntax OK.
  2. Lint: cookstyle hello.rb reports Ruby style problems and Chef-specific issues. A clean result ends with no offenses detected. cookstyle -a hello.rb fixes the issues it can correct automatically.
  3. Dry run: chef-apply hello.rb --why-run (short form -W) shows what would change without changing it.
  4. Converge twice: the second run must report every resource as (up to date). Changes on every run point to a non-idempotent resource, usually an execute or bash block without a guard.
  5. Verify the end state with Chef InSpec, as shown below.

Save this InSpec control as verify.rb:

describe file('/tmp/devopsschool/index.html') do
  it { should exist }
  it { should be_file }
  its('mode') { should cmp '0644' }
  its('content') { should match /Hello everyone from DevOpsSchool/ }
endCode language: JavaScript (javascript)
inspec exec verify.rb --chef-license accept
# With no --target option, InSpec checks the local machine.
# Expected summary: 4 successful, 0 failures, 0 skippedCode language: PHP (php)

When the recipe moves into a cookbook (chef generate cookbook my_cookbook), the same ideas grow into ChefSpec unit tests (chef exec rspec) and Test Kitchen integration tests (kitchen test). Test Kitchen converges the cookbook on a fresh VM or container and then runs InSpec against it. For more on InSpec itself, see What is Chef InSpec and How it works?.

Note: Why-run mode makes assumptions. If a later resource depends on an earlier one, such as a service whose package is not installed yet, why-run assumes the earlier step would have succeeded. Treat its output as a forecast, not a guarantee.

Useful chef-apply options

OptionPurpose
-W, --why-runShow what would change without modifying the system
-l debug, --log_level debugVerbose logging for troubleshooting resource decisions
-e 'RECIPE_TEXT'Run recipe code passed on the command line instead of from a file
-s, --stdinRead the recipe from standard input
--chef-license acceptAccept the Chef license non-interactively
--minimal-ohaiCollect only essential system data, so runs start faster
chef-apply -e "file '/tmp/quick.txt' do content 'hi' end"Code language: JavaScript (javascript)

Common errors and fixes

SymptomCauseFix
chef-apply: command not foundChef Workstation is not installed or its bin directory is not on PATHReinstall, or open a new shell and run eval "$(chef shell-init bash)"
Run stops and asks to accept the license, or fails in CIThe license has not been acceptedAdd --chef-license accept or set CHEF_LICENSE=accept
Permission denied on a path such as /var/www/htmlThe user cannot write to that locationRun with sudo or choose a writable path
SyntaxError or unexpected end-of-inputA missing end or an unbalanced quote in the RubyRun chef exec ruby -c hello.rb and fix the reported line
index.html is not where you expectedA relative path was usedUse an absolute path in the resource name

Frequently asked questions

What is the difference between chef-apply and chef-client?

chef-apply runs a single recipe file directly, with no cookbook, run-list or server, which makes it ideal for learning and quick tests. chef-client runs cookbooks from a run-list, either against a Chef Infra Server or locally with chef-client --local-mode (-z).

Does why-run mode change anything on the system?

No. --why-run evaluates every resource and reports what it would do, but makes no changes. Because it cannot see the results of earlier changes, its output for dependent resources is based on assumptions.

How do I know my Chef recipe is idempotent?

Run it twice in a row. On the second run every resource should report (up to date) and the summary should show no resources updated.

Can I test a Chef recipe without a Chef Infra Server?

Yes. chef-apply, Cookstyle, ChefSpec, Test Kitchen and InSpec all work locally from Chef Workstation. A server is only needed to manage nodes centrally.

Where does chef-apply create a file when the path is relative?

In the current working directory of the shell where you ran chef-apply. Use absolute paths in recipes so the result does not depend on where the command is run.

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: 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…

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
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x