Skip to main content

Chef/Correctness/RubyGuardWithoutBlock

Cookstyle cops page

The Cookstyle cops department: Chef/Correctness

Enabled by defaultSupports autocorrectionTarget Chef Version
EnabledYesAll Versions

A not_if/only_if guard takes either a string, which is run as a shell command, or a block, which is run as Ruby. Passing a Ruby expression directly gives the guard the expression’s result rather than the expression, because it is evaluated while the recipe is compiled.

A guard that receives true or false raises at converge time:

ArgumentError: Invalid only_if/not_if command, expected a string: true (TrueClass)

Worse, an expression that happens to return a string is accepted and then run as a shell command, so the guard quietly tests something entirely different to what was intended.

Only expressions that clearly produce a boolean are flagged, so a shell command built in Ruby and held in a variable is left alone.

Examples

# bad
not_if ::File.exist?('/etc/foo')
only_if node['foo']['version'] == '1.0'

# good
not_if { ::File.exist?('/etc/foo') }
only_if { node['foo']['version'] == '1.0' }

# good - a string guard runs as a shell command
not_if 'test -f /etc/foo'

Configurable attributes

NameDefault valueConfigurable values
Version Added9.0.0String
Include
    Array

    Thank you for your feedback!

    ×