Chef/Correctness/EmptyResourceGuard
The Cookstyle cops department: Chef/Correctness
| Enabled by default | Supports autocorrection | Target Chef Version |
|---|---|---|
| Enabled | No | All Versions |
Resource guards (not_if/only_if) should not be empty. An empty string always evaluates to true and an empty block always evaluates to false, so in either case the guard stops doing the job it was written for and the resource silently runs, or fails to run, on every converge.
Empty strings in Ruby are “truthy”, which means:
only_if ''will ALWAYS execute the resource (guard always passes)not_if ''will NEVER execute the resource (guard always blocks)
An empty block behaves the other way around, since a block with no body returns nil:
only_if { }will NEVER execute the resourcenot_if { }will ALWAYS execute the resource
This behavior is usually unintended and can lead to resources running when they shouldn’t or never running when they should.
Examples
# bad
template '/etc/foo' do
mode '0644'
source 'foo.erb'
only_if '' # This will always be true - resource always executes
end
cookbook_file '/logs/foo/error.log' do
source 'error.log'
not_if { '' } # This will always be true - resource never executes
end
service 'apache2' do
action :restart
only_if { '' } # Block form also problematic
end
# good
template '/etc/foo' do
mode '0644'
source 'foo.erb'
only_if 'test -f /etc/foo' # Actual shell command
end
cookbook_file '/logs/foo/error.log' do
source 'error.log'
not_if { ::File.exist?('/logs/foo/error.log') } # Proper Ruby expression
end
service 'apache2' do
action :restart
only_if { node['platform'] == 'ubuntu' } # Meaningful condition
end
# Or simply remove the guard if no condition is needed
package 'curl' do
action :install
end
Configurable attributes
| Name | Default value | Configurable values |
|---|---|---|
| Version Added | 8.4.0 | String |
| Include | Array |