Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Resources and Recipes

Guards and Idempotence in Chef

Learn Chef guards: only_if, not_if, creates, guard_interpreter and Ruby block guards, how they keep execute resources idempotent, and how to avoid common guard mistakes.

Resources such as package and file know how to check their own state. Others, especially execute, script and ruby_block, do not, so they would run every time. Guards fix that. A guard is a condition attached to any resource that decides whether the resource should run at all. Mastering guards is what separates recipes that are truly idempotent from recipes that "work" but report changes on every run.

only_if and not_if

Every resource accepts the properties only_if and not_if. Each takes either a string (a shell command, true if it exits with status 0) or a Ruby block (true if it returns a truthy value).

Ruby
execute 'initialize database' do
  command '/opt/app/bin/init-db'
  not_if { ::File.exist?('/var/lib/app/db.ready') }
end

execute 'enable maintenance mode' do
  command 'touch /var/www/maintenance'
  only_if 'test -f /etc/app/maintenance.flag'
end
  • only_if: run the resource only if the guard is true.
  • not_if: run the resource unless the guard is true.

Use the block form for Ruby checks (file exists, attribute set) and the string form for shell checks (a command's exit code). The block form is faster because it needs no new process. Inside a block guard, prefix file helpers with ::File to avoid a clash with the file resource's own methods.

creates, a shortcut for execute

execute has a special property: creates. The command runs only if the named file does not exist.

Ruby
execute 'extract archive' do
  command 'tar -xzf /tmp/app.tar.gz -C /opt/app'
  creates '/opt/app/bin/app'
end

This is the neatest way to make a one-off command idempotent. The success of the command should create the marker file, otherwise it will run again each time.

Guards are evaluated at converge time

Guard blocks run when Chef converges the resource, not when it compiles the recipe. So a guard can depend on something an earlier resource just did, which is a key advantage over plain Ruby if statements in the recipe body (those run at compile time, see the client run). Compare:

Ruby
# compile time: evaluated before anything converged
if ::File.exist?('/opt/app/bin/app')
  execute 'smoke test'
end

# converge time: evaluated just before this resource runs
execute 'smoke test' do
  only_if { ::File.exist?('/opt/app/bin/app') }
end

The second form is usually what you want.

Stand-in: a guard-aware resource

The stand-in implements only_if, not_if and creates for a fake execute, using lambdas for block guards. It is not real Chef.

Ruby Stand-in: only_if, not_if and creates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Run it and read each line: the first extract runs and creates its marker, the second is skipped, and the guards choose between the maintenance commands.

Multiple guards

You can give several guards: all only_if guards must be true and all not_if guards must be false. Pass an array of strings or blocks:

Ruby
execute 'reindex' do
  command '/opt/app/bin/reindex'
  only_if { node['app']['index_enabled'] }
  not_if  { ::File.exist?('/var/lock/reindex') }
end

Checking an expensive condition once

Guards run every Chef run, so a guard that runs a slow command slows everything down. Keep them cheap. When a check is slow, write the check result to a marker file that creates can test. The stand-in below counts how many times an expensive guard is called.

Ruby Stand-in: cheap versus expensive guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A marker file is a one-line check that never gets slower.

Common mistakes

  • No guard on execute. The resource runs and "changes" every time.
  • Guard command always fails or always succeeds. Test the command by hand and check echo $?.
  • Wrong direction. not_if means skip when true. Read it as "do this, unless ...".
  • Using Ruby if for runtime facts. The recipe-level if runs at compile time.

Chef also provides guard_interpreter :powershell_script so that a string guard on Windows is run as PowerShell instead of cmd. Set it on the resource that needs it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. not_if { ::File.exist?('/x') } on an execute resource means:

    not_if skips the resource when the guard is true.
  2. 2. What does the creates property of execute do?

    creates is an idempotence shortcut: the command is skipped when the file already exists.
  3. 3. When is a block guard evaluated?

    Guards run during converge, so they can react to earlier resources.
  4. 4. Why prefer a block guard over a string guard for simple Ruby checks?

    A Ruby block runs in the client's own process, while a string guard launches a shell command.

Summary

  • only_if runs a resource when true; not_if skips it when true.
  • Guards take shell command strings or Ruby blocks and run at converge time.
  • creates makes an execute idempotent with a marker file.
  • Keep guards cheap, test them by hand, and avoid compile-time if for runtime facts.

Next: Notifications and Subscribes