Method: Chef::Mixin::WhyRun::ResourceRequirements#assert

Defined in:
lib/chef/mixin/why_run.rb

#assert(*actions) {|assertion| ... } ⇒ Object

Define a new Assertion.

Takes a list of action names for which the assertion should be made.

Examples:

A File provider that requires the parent directory to exist:

assert(:create, :create_if_missing) do |a|
  parent_dir = File.basename(@new_resource.path)
  a.assertion { ::File.directory?(parent_dir) }
  a.failure_message(Exceptions::ParentDirectoryDoesNotExist,
                    "Can't create file #{@new_resource.path}: parent directory #{parent_dir} doesn't exist")
  a.why_run("assuming parent directory #{parent_dir} would have been previously created"
end

A service provider that requires the init script to exist:

assert(:start, :restart) do |a|
  a.assertion { ::File.exist?(@new_resource.init_script) }
  a.failure_message(Exceptions::MissingInitScript,
                    "Can't check status of #{@new_resource}: init script #{@new_resource.init_script} is missing")
  a.why_run("Assuming init script would have been created and service is stopped") do
    @current_resource.status(:stopped)
  end
end

A File provider that will error out if you don’t have permissions do delete the file, *even in why run mode*:

assert(:delete) do |a|
  a.assertion { ::File.writable?(@new_resource.path) }
  a.failure_message(Exceptions::InsufficientPrivileges,
                    "You don't have sufficient privileges to delete #{@new_resource.path}")
end

A Template provider that will prevent action execution but continue the run in whyrun mode if the template source is not available.

assert(:create, :create_if_missing) do |a| 
  a.assertion { File::exist?(@new_resource.source) }
  a.failure_message Chef::Exceptions::TemplateError, "Template #{@new_resource.source} could not be found exist."
  a.whyrun "Template source #{@new_resource.source} does not exist. Assuming it would have been created."
  a.block_action!
end

assert(:delete) do |a|
  a.assertion { ::File.writable?(@new_resource.path) }
  a.failure_message(Exceptions::InsufficientPrivileges,
                    "You don't have sufficient privileges to delete #{@new_resource.path}")
end

Yields:

  • (assertion)


320
321
322
323
324
# File 'lib/chef/mixin/why_run.rb', line 320

def assert(*actions)
  assertion = Assertion.new
  yield assertion
  actions.each {|action| @assertions[action] << assertion }
end