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.rbline 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.htmlis 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:
- Syntax check:
chef exec ruby -c hello.rbshould printSyntax OK. - Lint:
cookstyle hello.rbreports Ruby style problems and Chef-specific issues. A clean result ends withno offenses detected.cookstyle -a hello.rbfixes the issues it can correct automatically. - Dry run:
chef-apply hello.rb --why-run(short form-W) shows what would change without changing it. - Converge twice: the second run must report every resource as
(up to date). Changes on every run point to a non-idempotent resource, usually anexecuteorbashblock without a guard. - 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
| Option | Purpose |
|---|---|
-W, --why-run | Show what would change without modifying the system |
-l debug, --log_level debug | Verbose logging for troubleshooting resource decisions |
-e 'RECIPE_TEXT' | Run recipe code passed on the command line instead of from a file |
-s, --stdin | Read the recipe from standard input |
--chef-license accept | Accept the Chef license non-interactively |
--minimal-ohai | Collect 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
| Symptom | Cause | Fix |
|---|---|---|
chef-apply: command not found | Chef Workstation is not installed or its bin directory is not on PATH | Reinstall, or open a new shell and run eval "$(chef shell-init bash)" |
| Run stops and asks to accept the license, or fails in CI | The license has not been accepted | Add --chef-license accept or set CHEF_LICENSE=accept |
Permission denied on a path such as /var/www/html | The user cannot write to that location | Run with sudo or choose a writable path |
SyntaxError or unexpected end-of-input | A missing end or an unbalanced quote in the Ruby | Run chef exec ruby -c hello.rb and fix the reported line |
index.html is not where you expected | A relative path was used | Use 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
- What is Chef and use cases of Chef?
- What is Chef InSpec and How it works? An Overview and Its Use Cases
- Chef Tutorials: knife command line reference
- More Chef tutorials
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