Class: RuboCop::Cop::Chef::Correctness::EmptyResourceGuard

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/chef/correctness/empty_resource_guard.rb

Overview

Resource guards (not_if/only_if) should not be empty strings as empty strings will always evaluate to true. This will cause confusion in your cookbooks as the guard will always pass.

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)

This behavior is usually unintended and can lead to resources running when they shouldn’t or never running when they should.

Examples:


### incorrect
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

### correct
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

Constant Summary collapse

MSG =
'Resource guards (not_if/only_if) should not be empty strings as empty strings will always evaluate to true.'
RESTRICT_ON_SEND =
[:not_if, :only_if].freeze

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#empty_string?(str) ⇒ Boolean

Returns:

  • (Boolean)


85
86
87
# File 'lib/rubocop/cop/chef/correctness/empty_resource_guard.rb', line 85

def empty_string?(str)
  str.empty?
end

#on_block(node) ⇒ Object



95
96
97
98
99
# File 'lib/rubocop/cop/chef/correctness/empty_resource_guard.rb', line 95

def on_block(node)
  empty_string_block_guard?(node) do
    add_offense(node, severity: :refactor)
  end
end

#on_send(node) ⇒ Object



89
90
91
92
93
# File 'lib/rubocop/cop/chef/correctness/empty_resource_guard.rb', line 89

def on_send(node)
  empty_string_guard?(node) do
    add_offense(node, severity: :refactor)
  end
end