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 a Ruby block. This page explains how guards differ from plain Ruby if statements and gives a recipe you can run. It also covers guard_interpreter and fixes several mistakes in the gist examples above.
Guards
A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:
A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied.
String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.


Guards versus Ruby if statements
A Chef Infra Client run has two phases. In the compile phase, Chef reads every recipe and builds a list of resources called the resource collection. In the converge phase, it works through that list and applies each resource. The examples above mix two kinds of conditions, and each kind runs in a different phase.
| Technique | Evaluated when | Effect |
|---|---|---|
Ruby if / unless / case around a resource | Compile phase | The resource is either added to the resource collection or never exists |
include_recipe ... if condition | Compile phase | The whole recipe is loaded or not |
not_if / only_if guard | Converge phase, just before the resource runs | The resource exists but is skipped, and the log shows (skipped due to not_if) or (skipped due to only_if) |
Use a Ruby if for facts that are known before anything changes, such as the platform, the platform version or the value of an attribute. Use a guard when the condition depends on system state that an earlier resource in the same run may change, such as a file, a user or a running service. A Ruby if that checks for a file created earlier in the same run is evaluated before that file exists. That is a common cause of resources that only work on the second run.
not_if and only_if syntax at a glance
not_if: the resource is skipped if the condition is true (block) or if the command exits with0(string).only_if: the resource runs only if the condition is true (block) or if the command exits with0(string).- Block guards are Ruby. Any truthy value counts as true, and
nilorfalsecounts as false. - String guards run as shell commands. They cost a process fork, so prefer a Ruby block when the check is simple, such as testing whether a file exists.
- One resource can have several guards. It runs only when every
only_ifpasses and nonot_ifmatches.
String guards accept options. The examples above use the older hash-rocket syntax (:user => 'adam'), which still works. Modern cookbooks normally use Ruby keyword-style hashes:
not_if 'grep adam /etc/passwd', user: 'adam'
not_if 'grep adam /etc/passwd', group: 'adam'
not_if 'grep adam /etc/passwd', environment: { 'HOME' => '/home/adam' }
not_if 'grep adam passwd', cwd: '/etc'
not_if 'sleep 10000', timeout: 10Code language: PHP (php)
A complete recipe you can run
The cookbook below uses both kinds of condition. Create it with Chef Workstation by running chef generate cookbook cookbooks/guards_demo, then replace recipes/default.rb with the following:
# cookbooks/guards_demo/recipes/default.rb
# Compile-time decision: the resource only exists on Debian-family nodes
if platform_family?('debian')
apt_update 'refresh apt cache' do
frequency 86_400
action :periodic
end
end
package 'tar'
directory '/opt/app' do
mode '0755'
end
# Ruby block guard, evaluated at converge time
file '/tmp/guards-demo.txt' do
content "managed by Chef\n"
mode '0644'
not_if { ::File.exist?('/tmp/guards-demo.lock') }
end
# Two guards: the archive must exist AND the app must not already be extracted
execute 'extract release' do
command 'tar -xzf /tmp/app.tar.gz -C /opt/app'
only_if { ::File.exist?('/tmp/app.tar.gz') }
not_if { ::File.exist?('/opt/app/VERSION') }
end
# String guard: getent exits 0 if the user exists, so the command is skipped
execute 'create demo user' do
command 'useradd --system --no-create-home demoapp'
not_if 'getent passwd demoapp'
endCode language: PHP (php)
Run it in local mode from the directory that contains cookbooks/:
sudo chef-client -z --chef-license accept -o 'recipe[guards_demo]'Code language: JavaScript (javascript)
If /tmp/app.tar.gz does not exist, the output includes lines like these:
* file[/tmp/guards-demo.txt] action create
- create new file /tmp/guards-demo.txt
* execute[extract release] action run (skipped due to only_if)
* execute[create demo user] action run
- execute useradd --system --no-create-home demoappCode language: JavaScript (javascript)
Run the same command again. This time create demo user reports (skipped due to not_if). That shows the guard is making an execute resource idempotent, meaning it only makes a change when one is needed. In a real cookbook, use the built-in user resource for this task. The execute example is only here to show how a string guard works.
guard_interpreter and inherited properties
By default, a string guard runs as a plain shell command. It does not see the environment, user or other properties you set on the resource. That is why the first bash "some_app" example above fails: JAVA_HOME is set for code but not for the not_if command.
Setting guard_interpreter to the resource's own type (for example :bash) runs the guard through that interpreter. The guard then inherits properties such as cwd, environment, user, group and umask from the parent resource. powershell_script already defaults to :powershell_script, so its guards inherit these properties and can return a PowerShell boolean as well as an exit code.
bash 'some_app' do
guard_interpreter :bash
environment('JAVA_HOME' => '/usr/java/default')
code 'java /apps/some_app/app start'
not_if 'java /apps/some_app/app status' # also sees JAVA_HOME
endCode language: PHP (php)
Note: guard_interpreter only affects string guards. Block guards are always Ruby and run inside the Chef Infra Client process.
Corrected versions of the gist examples
The gist above mixes code with notes that are not commented out, so it cannot run as one file. The examples below fix the specific errors in it.
# 1. environment { ... } is parsed as a Ruby block, not a Hash -> syntax error.
# Use parentheses (or drop the braces).
bash 'some_app' do
environment('JAVA_HOME' => '/usr/java/default')
code 'java /apps/some_app/app start'
not_if 'java /apps/some_app/app status', environment: { 'JAVA_HOME' => '/usr/java/default' }
end
# 2. The comment said "only on RHEL 6.x", but not_if { rhel && < 6.0 } also
# installs on every non-RHEL node, and >= 6.0 matches RHEL 7, 8, 9...
package 'package_name' do
only_if { platform_family?('rhel') && node['platform_version'].to_i == 6 }
end
# 3. include_recipe is a method, not a resource: a do...end block with
# only_if is ignored, and '=' assigns instead of comparing.
include_recipe 'postfix::server' if node['defaults']['postfix_server']
# 4. Prefer built-in resources over execute for package work.
apt_update 'update' if platform_family?('debian')
package 'git' if platform_family?('rhel')
# 5. Guard an apt_package with a positive platform check.
package 'apache2' do
only_if { platform_family?('debian') }
end
# 6. String#include? does substring matching; use the helper instead.
if platform_family?('rhel')
# ...
endCode language: PHP (php)
Common mistakes and how to fix them
| Symptom | Cause | Fix |
|---|---|---|
Resource runs every time despite not_if | The string guard depends on variables or a working directory that it does not receive | Pass environment: or cwd: to the guard, or set guard_interpreter |
| Resource only works on the second run | A Ruby if checked state that an earlier resource creates in the same run | Move the check into an only_if or not_if block |
only_if on include_recipe has no effect | include_recipe does not accept guards | Wrap the call in a Ruby if |
NameError or odd behaviour with File.exist? in custom resources | File can resolve to a Chef class inside resource code | Use ::File.exist? to reference Ruby's top-level File class |
| Guard is always true | Assignment (=) used instead of comparison (==) | Use == or test the attribute value directly |
Best practices
- Prefer idempotent built-in resources (
package,user,service,apt_update) toexecute. They already check state themselves, so you need fewer guards. - For
execute, use thecreatesproperty when the only check is whether a file exists:creates '/opt/app/VERSION'. - Prefer Ruby block guards to shell strings for simple checks. They are faster and do not depend on the shell or the
PATH. - Use the platform helpers (
platform?,platform_family?) and string attribute keys such asnode['platform']rather than comparing raw strings or using symbol keys. - Keep guards read-only. A guard command that changes the system makes the run unpredictable.
- Retire conditions for end-of-life platforms such as RHEL 6, and outdated package names such as
php5, when you maintain older cookbooks.
Frequently asked questions
What is the difference between not_if and only_if in Chef?
not_if skips the resource when its condition is true or its command exits with 0. only_if runs the resource only when its condition is true or its command exits with 0. Each is the logical opposite of the other.
Can a Chef resource have both not_if and only_if?
Yes. A resource can have several guards of either type. It runs only when every only_if passes and none of the not_if conditions match.
Should I use a Ruby if statement or a guard in a Chef recipe?
Use a Ruby if for facts known at compile time, such as the platform or attribute values. Use a guard when the condition depends on system state that may change during the run, because guards are evaluated at converge time.
Why does my string guard not see the environment variables set on the resource?
By default, string guards run as separate shell commands and do not inherit resource properties. Pass environment: to the guard, or set guard_interpreter to the resource type, such as :bash, so the guard inherits environment, cwd, user and similar properties.
Can I use only_if with include_recipe?
No. include_recipe is a method, not a resource, so guard properties have no effect on it. Use a Ruby condition such as include_recipe 'postfix::server' if node['defaults']['postfix_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