Class: Chef::Resource

Inherits:
Object show all
Extended by:
Mixin::ConvertToClassName
Includes:
DSL::DataQuery, DSL::PlatformIntrospection, DSL::RebootPending, DSL::RegistryHelper, Mixin::ConvertToClassName, Mixin::Deprecation, Mixin::ParamsValidate
Defined in:
lib/chef/resource.rb,
lib/chef/resource/csh.rb,
lib/chef/resource/env.rb,
lib/chef/resource/git.rb,
lib/chef/resource/log.rb,
lib/chef/resource/scm.rb,
lib/chef/resource/bash.rb,
lib/chef/resource/cron.rb,
lib/chef/resource/file.rb,
lib/chef/resource/link.rb,
lib/chef/resource/ohai.rb,
lib/chef/resource/perl.rb,
lib/chef/resource/ruby.rb,
lib/chef/resource/user.rb,
lib/chef/resource/batch.rb,
lib/chef/resource/group.rb,
lib/chef/resource/mdadm.rb,
lib/chef/resource/mount.rb,
lib/chef/resource/route.rb,
lib/chef/resource/deploy.rb,
lib/chef/resource/python.rb,
lib/chef/resource/script.rb,
lib/chef/resource/execute.rb,
lib/chef/resource/package.rb,
lib/chef/resource/service.rb,
lib/chef/resource/chef_gem.rb,
lib/chef/resource/erl_call.rb,
lib/chef/resource/ifconfig.rb,
lib/chef/resource/template.rb,
lib/chef/resource/directory.rb,
lib/chef/resource/lwrp_base.rb,
lib/chef/resource/breakpoint.rb,
lib/chef/resource/ruby_block.rb,
lib/chef/resource/subversion.rb,
lib/chef/resource/apt_package.rb,
lib/chef/resource/bff_package.rb,
lib/chef/resource/conditional.rb,
lib/chef/resource/gem_package.rb,
lib/chef/resource/ips_package.rb,
lib/chef/resource/remote_file.rb,
lib/chef/resource/rpm_package.rb,
lib/chef/resource/yum_package.rb,
lib/chef/resource/dpkg_package.rb,
lib/chef/resource/http_request.rb,
lib/chef/resource/registry_key.rb,
lib/chef/resource_platform_map.rb,
lib/chef/resource/cookbook_file.rb,
lib/chef/resource/pacman_package.rb,
lib/chef/resource/windows_script.rb,
lib/chef/resource/deploy_revision.rb,
lib/chef/resource/freebsd_package.rb,
lib/chef/resource/portage_package.rb,
lib/chef/resource/smartos_package.rb,
lib/chef/resource/solaris_package.rb,
lib/chef/resource/windows_package.rb,
lib/chef/resource/macports_package.rb,
lib/chef/resource/remote_directory.rb,
lib/chef/resource/powershell_script.rb,
lib/chef/resource/timestamped_deploy.rb,
lib/chef/resource/easy_install_package.rb,
lib/chef/resource/whyrun_safe_ruby_block.rb,
lib/chef/resource/conditional_action_not_nothing.rb

Defined Under Namespace

Classes: AptPackage, Bash, Batch, BffPackage, Breakpoint, ChefGem, Conditional, ConditionalActionNotNothing, CookbookFile, Cron, Csh, Deploy, DeployBranch, DeployRevision, Directory, DpkgPackage, EasyInstallPackage, Env, ErlCall, Execute, File, FreebsdPackage, GemPackage, Git, Group, HttpRequest, Ifconfig, IpsPackage, LWRPBase, Link, Log, MacportsPackage, Mdadm, Mount, Notification, Ohai, Package, PacmanPackage, Perl, PlatformMap, PortagePackage, PowershellScript, Python, RegistryKey, RemoteDirectory, RemoteFile, Route, RpmPackage, Ruby, RubyBlock, Scm, Script, Service, SmartosPackage, SolarisPackage, Subversion, Template, TimestampedDeploy, User, WhyrunSafeRubyBlock, WindowsPackage, WindowsScript, YumPackage

Constant Summary collapse

FORBIDDEN_IVARS =
[:@run_context, :@node, :@not_if, :@only_if, :@enclosing_provider]
HIDDEN_IVARS =
[:@allowed_actions, :@resource_name, :@source_line, :@run_context, :@name, :@node, :@not_if, :@only_if, :@elapsed_time, :@enclosing_provider]
SmartOSPackage =
TODO:

remove in Chef 12

Backwards compatability

Chef::Resource::SmartosPackage

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixin::ConvertToClassName

convert_to_class_name, convert_to_snake_case, filename_to_qualified_string, snake_case_basename

Methods included from Mixin::Deprecation

#deprecated_ivar

Methods included from DSL::RebootPending

#reboot_pending?

Methods included from DSL::PlatformIntrospection

#platform?, #platform_family?, #value_for_platform, #value_for_platform_family

Methods included from DSL::RegistryHelper

#registry_data_exists?, #registry_get_subkeys, #registry_get_values, #registry_has_subkeys?, #registry_key_exists?, #registry_value_exists?

Methods included from Mixin::ParamsValidate

#lazy, #set_or_return, #validate

Methods included from DSL::DataQuery

#data_bag, #data_bag_item, #search

Constructor Details

#initialize(name, run_context = nil) ⇒ Resource

Each notify entry is a resource/action pair, modeled as an Struct with a #resource and #action member



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/chef/resource.rb', line 235

def initialize(name, run_context=nil)
  @name = name
  @run_context = run_context
  @noop = nil
  @before = nil
  @params = Hash.new
  @provider = nil
  @allowed_actions = [ :nothing ]
  @action = :nothing
  @updated = false
  @updated_by_last_action = false
  @supports = {}
  @ignore_failure = false
  @retries = 0
  @retry_delay = 2
  @not_if = []
  @only_if = []
  @source_line = nil
  @guard_interpreter = :default
  @elapsed_time = 0

  @node = run_context ? deprecated_ivar(run_context.node, :node, :warn) : nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_symbol, *args, &block) ⇒ Object

If an unknown method is invoked, determine whether the enclosing Provider’s lexical scope can fulfill the request. E.g. This happens when the Resource’s block invokes new_resource.



294
295
296
297
298
299
300
# File 'lib/chef/resource.rb', line 294

def method_missing(method_symbol, *args, &block)
  if enclosing_provider && enclosing_provider.respond_to?(method_symbol)
    enclosing_provider.send(method_symbol, *args, &block)
  else
    raise NoMethodError, "undefined method `#{method_symbol.to_s}' for #{self.class.to_s}"
  end
end

Instance Attribute Details

#allowed_actionsObject

Returns the value of attribute allowed_actions.



215
216
217
# File 'lib/chef/resource.rb', line 215

def allowed_actions
  @allowed_actions
end

#cookbook_nameObject

Returns the value of attribute cookbook_name.



217
218
219
# File 'lib/chef/resource.rb', line 217

def cookbook_name
  @cookbook_name
end

#elapsed_timeObject (readonly)

Returns the value of attribute elapsed_time.



230
231
232
# File 'lib/chef/resource.rb', line 230

def elapsed_time
  @elapsed_time
end

#enclosing_providerObject

Returns the value of attribute enclosing_provider.



219
220
221
# File 'lib/chef/resource.rb', line 219

def enclosing_provider
  @enclosing_provider
end

#not_if_argsObject (readonly)

Returns the value of attribute not_if_args.



227
228
229
# File 'lib/chef/resource.rb', line 227

def not_if_args
  @not_if_args
end

#only_if_argsObject (readonly)

Returns the value of attribute only_if_args.



228
229
230
# File 'lib/chef/resource.rb', line 228

def only_if_args
  @only_if_args
end

#paramsObject

Returns the value of attribute params.



213
214
215
# File 'lib/chef/resource.rb', line 213

def params
  @params
end

#provider(arg = nil) ⇒ Object

Returns the value of attribute provider.



214
215
216
# File 'lib/chef/resource.rb', line 214

def provider
  @provider
end

#recipe_nameObject

Returns the value of attribute recipe_name.



218
219
220
# File 'lib/chef/resource.rb', line 218

def recipe_name
  @recipe_name
end

#resource_nameObject (readonly)

Returns the value of attribute resource_name.



226
227
228
# File 'lib/chef/resource.rb', line 226

def resource_name
  @resource_name
end

#retries(arg = nil) ⇒ Object

Returns the value of attribute retries.



221
222
223
# File 'lib/chef/resource.rb', line 221

def retries
  @retries
end

#retry_delay(arg = nil) ⇒ Object

Returns the value of attribute retry_delay.



222
223
224
# File 'lib/chef/resource.rb', line 222

def retry_delay
  @retry_delay
end

#run_contextObject

Returns the value of attribute run_context.



216
217
218
# File 'lib/chef/resource.rb', line 216

def run_context
  @run_context
end

#source_lineObject

Returns the value of attribute source_line.



220
221
222
# File 'lib/chef/resource.rb', line 220

def source_line
  @source_line
end

#updatedObject

Returns the value of attribute updated.



224
225
226
# File 'lib/chef/resource.rb', line 224

def updated
  @updated
end

Class Method Details

.dsl_nameObject



209
210
211
# File 'lib/chef/resource.rb', line 209

def self.dsl_name
  convert_to_snake_case(name, 'Chef::Resource')
end

.find_subclass_by_name(class_name) ⇒ Object

Look up a subclass by class_name which should be a string that matches Subclass.name



163
164
165
# File 'lib/chef/resource.rb', line 163

def self.find_subclass_by_name(class_name)
  resource_classes.first {|c| c.name == class_name }
end

.identity_attr(attr_name = nil) ⇒ Object

Set or return the “identity attribute” for this resource class. This is generally going to be the “name attribute” for this resource. In other words, the resource type plus this attribute uniquely identify a given bit of state that chef manages. For a File resource, this would be the path, for a package resource, it will be the package name. This will show up in chef-client’s audit records as a searchable field.



197
198
199
200
201
202
203
204
205
206
207
# File 'lib/chef/resource.rb', line 197

def self.identity_attr(attr_name=nil)
  @identity_attr ||= nil
  @identity_attr = attr_name if attr_name

  # If this class doesn't have an identity attr, we'll defer to the superclass:
  if @identity_attr || !superclass.respond_to?(:identity_attr)
    @identity_attr
  else
    superclass.identity_attr
  end
end

.inherited(subclass) ⇒ Object

Callback when subclass is defined. Adds subclass to list of subclasses.



157
158
159
# File 'lib/chef/resource.rb', line 157

def self.inherited(subclass)
  resource_classes << subclass
end

.json_create(o) ⇒ Object



722
723
724
725
726
727
728
# File 'lib/chef/resource.rb', line 722

def self.json_create(o)
  resource = self.new(o["instance_vars"]["@name"])
  o["instance_vars"].each do |k,v|
    resource.instance_variable_set("@#{k}".to_sym, v)
  end
  resource
end

.platform_mapObject



747
748
749
# File 'lib/chef/resource.rb', line 747

def self.platform_map
  @@platform_map ||= PlatformMap.new
end

.provider_base(arg = nil) ⇒ Object

Resources that want providers namespaced somewhere other than Chef::Provider can set the namespace with provider_base Ex:

class MyResource < Chef::Resource
  provider_base Chef::Provider::Deploy
  # ...other stuff
end


742
743
744
745
# File 'lib/chef/resource.rb', line 742

def self.provider_base(arg=nil)
  @provider_base ||= arg
  @provider_base ||= Chef::Provider
end

.provides(short_name, opts = {}) ⇒ Object

Maps a short_name (and optionally a platform and version) to a Chef::Resource. This allows finer grained per platform resource attributes and the end of overloaded resource definitions (I’m looking at you Chef::Resource::Package) Ex:

class WindowsFile < Chef::Resource
  provides :file, :on_platforms => ["windows"]
  # ...other stuff
end

TODO: 2011-11-02 schisamo - platform_version support



762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'lib/chef/resource.rb', line 762

def self.provides(short_name, opts={})
  short_name_sym = short_name
  if short_name.kind_of?(String)
    short_name.downcase!
    short_name.gsub!(/\s/, "_")
    short_name_sym = short_name.to_sym
  end
  if opts.has_key?(:on_platforms)
    platforms = [opts[:on_platforms]].flatten
    platforms.each do |p|
      p = :default if :all == p.to_sym
      platform_map.set(
        :platform => p.to_sym,
        :short_name => short_name_sym,
        :resource => self
      )
    end
  else
    platform_map.set(
      :short_name => short_name_sym,
      :resource => self
    )
  end
end

.resource_classesObject

Track all subclasses of Resource. This is used so names can be looked up when attempting to deserialize from JSON. (See: json_compat)



149
150
151
152
153
154
# File 'lib/chef/resource.rb', line 149

def self.resource_classes
  # Using a class variable here ensures we have one variable to track
  # subclasses shared by the entire class hierarchy; without this, each
  # subclass would have its own list of subclasses.
  @@resource_classes ||= []
end

.resource_for_node(short_name, node) ⇒ Object

Returns a resource based on a short_name and a node’s platform and version.

Parameters

short_name<Symbol>

short_name of the resource (ie :directory)

node<Chef::Node>

Node object to look up platform and version in

Returns

<Chef::Resource>

returns the proper Chef::Resource class



810
811
812
813
814
815
816
817
# File 'lib/chef/resource.rb', line 810

def self.resource_for_node(short_name, node)
  begin
    platform, version = Chef::Platform.find_platform_and_version(node)
  rescue ArgumentError
  end
  resource = resource_for_platform(short_name, platform, version)
  resource
end

.resource_for_platform(short_name, platform = nil, version = nil) ⇒ Object

Returns a resource based on a short_name anda platform and version.

Parameters

short_name<Symbol>

short_name of the resource (ie :directory)

platform<Symbol,String>

platform name

version<String>

platform version

Returns

<Chef::Resource>

returns the proper Chef::Resource class



797
798
799
# File 'lib/chef/resource.rb', line 797

def self.resource_for_platform(short_name, platform=nil, version=nil)
  platform_map.get(short_name, platform, version)
end

.state_attrs(*attr_names) ⇒ Object

Set or return the list of “state attributes” implemented by the Resource subclass. State attributes are attributes that describe the desired state of the system, such as file permissions or ownership. In general, state attributes are attributes that could be populated by examining the state of the system (e.g., File.stat can tell you the permissions on an existing file). Contrarily, attributes that are not “state attributes” usually modify the way Chef itself behaves, for example by providing additional options for a package manager to use when installing a package.

This list is used by the Chef client auditing system to extract information from resources to describe changes made to the system.



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/chef/resource.rb', line 179

def self.state_attrs(*attr_names)
  @state_attrs ||= []
  @state_attrs = attr_names unless attr_names.empty?

  # Return *all* state_attrs that this class has, including inherited ones
  if superclass.respond_to?(:state_attrs)
    superclass.state_attrs + @state_attrs
  else
    @state_attrs
  end
end

.strict_const_defined?(const) ⇒ Boolean

Returns:

  • (Boolean)


138
139
140
# File 'lib/chef/resource.rb', line 138

def self.strict_const_defined?(const)
  const_defined?(const)
end

Instance Method Details

#action(arg = nil) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/chef/resource.rb', line 342

def action(arg=nil)
  if arg
    action_list = arg.kind_of?(Array) ? arg : [ arg ]
    action_list = action_list.collect { |a| a.to_sym }
    action_list.each do |action|
      validate(
        {
          :action => action,
        },
        {
          :action => { :kind_of => Symbol, :equal_to => @allowed_actions },
        }
      )
    end
    @action = action_list
  else
    @action
  end
end

#after_createdObject

Hook to allow a resource to run specific code after creation



731
732
733
# File 'lib/chef/resource.rb', line 731

def after_created
  nil
end

#as_json(*a) ⇒ Object

as_json does most of the to_json heavy lifted. It exists here in case activesupport is loaded. activesupport will call as_json and skip over to_json. This ensure json is encoded as expected



521
522
523
524
525
526
527
528
529
530
531
# File 'lib/chef/resource.rb', line 521

def as_json(*a)
  safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS
  instance_vars = Hash.new
  safe_ivars.each do |iv|
    instance_vars[iv.to_s.sub(/^@/, '')] = instance_variable_get(iv)
  end
  {
    'json_class' => self.class.name,
    'instance_vars' => instance_vars
  }
end

#cookbook_versionObject



606
607
608
609
610
# File 'lib/chef/resource.rb', line 606

def cookbook_version
  if cookbook_name
    run_context.cookbook_collection[cookbook_name]
  end
end

#custom_exception_message(e) ⇒ Object



675
676
677
# File 'lib/chef/resource.rb', line 675

def custom_exception_message(e)
  "#{self} (#{defined_at}) had an error: #{e.class.name}: #{e.message}"
end

#customize_exception(e) ⇒ Object



679
680
681
682
683
# File 'lib/chef/resource.rb', line 679

def customize_exception(e)
  new_exception = e.exception(custom_exception_message(e))
  new_exception.set_backtrace(e.backtrace)
  new_exception
end

#defined_atObject



591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'lib/chef/resource.rb', line 591

def defined_at
  # The following regexp should match these two sourceline formats:
  #   /some/path/to/file.rb:80:in `wombat_tears'
  #   C:/some/path/to/file.rb:80 in 1`wombat_tears'
  # extracting the path to the source file and the line number.
  (file, line_no) = source_line.match(/(.*):(\d+):?.*$/).to_a[1,2] if source_line
  if cookbook_name && recipe_name && source_line
    "#{cookbook_name}::#{recipe_name} line #{line_no}"
  elsif source_line
    "#{file} line #{line_no}"
  else
    "dynamically defined"
  end
end

#delayed_notificationsObject



457
458
459
# File 'lib/chef/resource.rb', line 457

def delayed_notifications
  run_context.delayed_notifications(self)
end

#epic_fail(arg = nil) ⇒ Object



402
403
404
# File 'lib/chef/resource.rb', line 402

def epic_fail(arg=nil)
  ignore_failure(arg)
end

#eventsObject



612
613
614
# File 'lib/chef/resource.rb', line 612

def events
  run_context.events
end

#guard_interpreter(arg = nil) ⇒ Object



406
407
408
409
410
411
412
# File 'lib/chef/resource.rb', line 406

def guard_interpreter(arg=nil)
  set_or_return(
    :guard_interpreter,
    arg,
    :kind_of => Symbol
  )
end

#identityObject

Returns the value of the identity attribute, if declared. Falls back to #name if no identity attribute is declared.



270
271
272
273
274
275
276
# File 'lib/chef/resource.rb', line 270

def identity
  if identity_attr = self.class.identity_attr
    send(identity_attr)
  else
    name
  end
end

#ignore_failure(arg = nil) ⇒ Object



378
379
380
381
382
383
384
# File 'lib/chef/resource.rb', line 378

def ignore_failure(arg=nil)
  set_or_return(
    :ignore_failure,
    arg,
    :kind_of => [ TrueClass, FalseClass ]
  )
end

#immediate_notificationsObject



453
454
455
# File 'lib/chef/resource.rb', line 453

def immediate_notifications
  run_context.immediate_notifications(self)
end

#inspectObject



511
512
513
514
515
516
# File 'lib/chef/resource.rb', line 511

def inspect
  ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS
  ivars.inject("<#{to_s}") do |str, ivar|
    str << " #{ivar}: #{instance_variable_get(ivar).inspect}"
  end << ">"
end

#is(*args) ⇒ Object



483
484
485
486
487
488
489
# File 'lib/chef/resource.rb', line 483

def is(*args)
  if args.size == 1
    args.first
  else
    return *args
  end
end

#load_prior_resourceObject



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/chef/resource.rb', line 302

def load_prior_resource
  begin
    prior_resource = run_context.resource_collection.lookup(self.to_s)
    # if we get here, there is a prior resource (otherwise we'd have jumped
    # to the rescue clause).
    Chef::Log.warn("Cloning resource attributes for #{self.to_s} from prior resource (CHEF-3694)")
    Chef::Log.warn("Previous #{prior_resource}: #{prior_resource.source_line}") if prior_resource.source_line
    Chef::Log.warn("Current  #{self}: #{self.source_line}") if self.source_line
    prior_resource.instance_variables.each do |iv|
      unless iv.to_sym == :@source_line || iv.to_sym == :@action || iv.to_sym == :@not_if || iv.to_sym == :@only_if
        self.instance_variable_set(iv, prior_resource.instance_variable_get(iv))
      end
    end
    true
  rescue Chef::Exceptions::ResourceNotFound
    true
  end
end

#name(name = nil) ⇒ Object



362
363
364
365
366
367
368
# File 'lib/chef/resource.rb', line 362

def name(name=nil)
  if !name.nil?
    raise ArgumentError, "name must be a string!" unless name.kind_of?(String)
    @name = name
  end
  @name
end

#nodeObject



287
288
289
# File 'lib/chef/resource.rb', line 287

def node
  run_context && run_context.node
end

#noop(tf = nil) ⇒ Object



370
371
372
373
374
375
376
# File 'lib/chef/resource.rb', line 370

def noop(tf=nil)
  if !tf.nil?
    raise ArgumentError, "noop must be true or false!" unless tf == true || tf == false
    @noop = tf
  end
  @noop
end

#not_if(command = nil, opts = {}, &block) ⇒ Object

If command is a block, returns false if the block returns true, true if it returns false. (“Do not run this resource if the block is true”)

If the command is not a block, executes the command. If it returns a 0 exitstatus, returns false. (“Do not run this resource if the command returns 0”)

Parameters

command<String>

A a string to execute.

opts<Hash>

Options control the execution of the command

block<Proc>

A ruby block to run. Ignored if a command is given.

Evaluation

  • evaluates to true if the block is false, or if the command returns a non-zero exit status.

  • evaluates to false if the block is true, or if the command returns a 0 exit status.



584
585
586
587
588
589
# File 'lib/chef/resource.rb', line 584

def not_if(command=nil, opts={}, &block)
  if command || block_given?
    @not_if << Conditional.not_if(self, command, opts, &block)
  end
  @not_if
end

#notifies(action, resource_spec, timing = :delayed) ⇒ Object

Sets up a notification from this resource to the resource specified by resource_spec.



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/chef/resource.rb', line 415

def notifies(action, resource_spec, timing=:delayed)
  # when using old-style resources(:template => "/foo.txt") style, you
  # could end up with multiple resources.
  resources = [ resource_spec ].flatten
  resources.each do |resource|

    validate_resource_spec!(resource_spec)

    case timing.to_s
    when 'delayed'
      notifies_delayed(action, resource)
    when 'immediate', 'immediately'
      notifies_immediately(action, resource)
    else
      raise ArgumentError,  "invalid timing: #{timing} for notifies(#{action}, #{resources.inspect}, #{timing}) resource #{self} "\
                            "Valid timings are: :delayed, :immediate, :immediately"
    end
  end

  true
end

#notifies_delayed(action, resource_spec) ⇒ Object



449
450
451
# File 'lib/chef/resource.rb', line 449

def notifies_delayed(action, resource_spec)
  run_context.notifies_delayed(Notification.new(resource_spec, action, self))
end

#notifies_immediately(action, resource_spec) ⇒ Object



445
446
447
# File 'lib/chef/resource.rb', line 445

def notifies_immediately(action, resource_spec)
  run_context.notifies_immediately(Notification.new(resource_spec, action, self))
end

#only_if(command = nil, opts = {}, &block) ⇒ Object

If command is a block, returns true if the block returns true, false if it returns false. (“Only run this resource if the block is true”)

If the command is not a block, executes the command. If it returns any status other than 0, it returns false (clearly, a 0 status code is true)

Parameters

command<String>

A a string to execute.

opts<Hash>

Options control the execution of the command

block<Proc>

A ruby block to run. Ignored if a command is given.

Evaluation

  • evaluates to true if the block is true, or if the command returns 0

  • evaluates to false if the block is false, or if the command returns a non-zero exit code.



563
564
565
566
567
568
# File 'lib/chef/resource.rb', line 563

def only_if(command=nil, opts={}, &block)
  if command || block_given?
    @only_if << Conditional.only_if(self, command, opts, &block)
  end
  @only_if
end

#provider_for_action(action) ⇒ Object



662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/chef/resource.rb', line 662

def provider_for_action(action)
  # leverage new platform => short_name => resource
  # which requires explicitly setting provider in
  # resource class
  if self.provider
    provider = self.provider.new(self, self.run_context)
    provider.action = action
    provider
  else # fall back to old provider resolution
    Chef::Platform.provider_for_resource(self, action)
  end
end

#resolve_notification_referencesObject

Iterates over all immediate and delayed notifications, calling resolve_resource_reference on each in turn, causing them to resolve lazy/forward references.



440
441
442
443
# File 'lib/chef/resource.rb', line 440

def resolve_notification_references
  run_context.immediate_notifications(self).each { |n| n.resolve_resource_reference(run_context.resource_collection) }
  run_context.delayed_notifications(self).each {|n| n.resolve_resource_reference(run_context.resource_collection) }
end

#resources(*args) ⇒ Object



461
462
463
# File 'lib/chef/resource.rb', line 461

def resources(*args)
  run_context.resource_collection.find(*args)
end

#run_action(action, notification_type = nil, notifying_resource = nil) ⇒ Object



616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/chef/resource.rb', line 616

def run_action(action, notification_type=nil, notifying_resource=nil)
  # reset state in case of multiple actions on the same resource.
  @elapsed_time = 0
  start_time = Time.now
  events.resource_action_start(self, action, notification_type, notifying_resource)
  # Try to resolve lazy/forward references in notifications again to handle
  # the case where the resource was defined lazily (ie. in a ruby_block)
  resolve_notification_references
  validate_action(action)

  if Chef::Config[:verbose_logging] || Chef::Log.level == :debug
    # This can be noisy
    Chef::Log.info("Processing #{self} action #{action} (#{defined_at})")
  end

  # ensure that we don't leave @updated_by_last_action set to true
  # on accident
  updated_by_last_action(false)

  begin
    return if should_skip?(action)
    provider_for_action(action).run_action
  rescue Exception => e
    if ignore_failure
      Chef::Log.error("#{custom_exception_message(e)}; ignore_failure is set, continuing")
      events.resource_failed(self, action, e)
    elsif retries > 0
      events.resource_failed_retriable(self, action, retries, e)
      @retries -= 1
      Chef::Log.info("Retrying execution of #{self}, #{retries} attempt(s) left")
      sleep retry_delay
      retry
    else
      events.resource_failed(self, action, e)
      raise customize_exception(e)
    end
  ensure
    @elapsed_time = Time.now - start_time
    events.resource_completed(self)
  end
end

#should_skip?(action) ⇒ Boolean

Evaluates not_if and only_if conditionals. Returns a falsey value if any of the conditionals indicate that this resource should be skipped, i.e., if an only_if evaluates to false or a not_if evaluates to true.

If this resource should be skipped, returns the first conditional that “fails” its check. Subsequent conditionals are not evaluated, so in general it’s not a good idea to rely on side effects from not_if or only_if commands/blocks being evaluated.

Also skips conditional checking when the action is :nothing

Returns:

  • (Boolean)


694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/chef/resource.rb', line 694

def should_skip?(action)
  conditional_action = ConditionalActionNotNothing.new(action)

  conditionals = [ conditional_action ] + only_if + not_if
  conditionals.find do |conditional|
    if conditional.continue?
      false
    else
      events.resource_skipped(self, action, conditional)
      Chef::Log.debug("Skipping #{self} due to #{conditional.description}")
      true
    end
  end
end

#stateObject

Returns a Hash of attribute => value for the state attributes declared in the resource’s class definition.



261
262
263
264
265
266
# File 'lib/chef/resource.rb', line 261

def state
  self.class.state_attrs.inject({}) do |state_attrs, attr_name|
    state_attrs[attr_name] = send(attr_name)
    state_attrs
  end
end

#subscribes(action, resources, timing = :delayed) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/chef/resource.rb', line 465

def subscribes(action, resources, timing=:delayed)
  resources = [resources].flatten
  resources.each do |resource|
    if resource.is_a?(String)
      resource = Chef::Resource.new(resource, run_context)
    end
    if resource.run_context.nil?
      resource.run_context = run_context
    end
    resource.notifies(action, self, timing)
  end
  true
end

#supports(args = {}) ⇒ Object



321
322
323
324
325
326
327
# File 'lib/chef/resource.rb', line 321

def supports(args={})
  if args.any?
    @supports = args
  else
    @supports
  end
end

#to_hashObject



539
540
541
542
543
544
545
546
547
# File 'lib/chef/resource.rb', line 539

def to_hash
  safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS
  instance_vars = Hash.new
  safe_ivars.each do |iv|
    key = iv.to_s.sub(/^@/,'').to_sym
    instance_vars[key] = instance_variable_get(iv)
  end
  instance_vars
end

#to_json(*a) ⇒ Object

Serialize this object as a hash



534
535
536
537
# File 'lib/chef/resource.rb', line 534

def to_json(*a)
  results = as_json
  results.to_json(*a)
end

#to_sObject



491
492
493
# File 'lib/chef/resource.rb', line 491

def to_s
  "#{@resource_name}[#{@name}]"
end

#to_textObject



495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/chef/resource.rb', line 495

def to_text
  ivars = instance_variables.map { |ivar| ivar.to_sym } - HIDDEN_IVARS
  text = "# Declared in #{@source_line}\n\n"
  text << self.class.dsl_name + "(\"#{name}\") do\n"
  ivars.each do |ivar|
    if (value = instance_variable_get(ivar)) && !(value.respond_to?(:empty?) && value.empty?)
      value_string = value.respond_to?(:to_text) ? value.to_text : value.inspect
      text << "  #{ivar.to_s.sub(/^@/,'')} #{value_string}\n"
    end
  end
  [@not_if, @only_if].flatten.each do |conditional|
    text << "  #{conditional.to_text}\n"
  end
  text << "end\n"
end

#updated?Boolean

Returns:

  • (Boolean)


718
719
720
# File 'lib/chef/resource.rb', line 718

def updated?
  updated
end

#updated_by_last_action(true_or_false) ⇒ Object



709
710
711
712
# File 'lib/chef/resource.rb', line 709

def updated_by_last_action(true_or_false)
  @updated ||= true_or_false
  @updated_by_last_action = true_or_false
end

#updated_by_last_action?Boolean

Returns:

  • (Boolean)


714
715
716
# File 'lib/chef/resource.rb', line 714

def updated_by_last_action?
  @updated_by_last_action
end

#validate_action(action) ⇒ Object

Raises:

  • (ArgumentError)


658
659
660
# File 'lib/chef/resource.rb', line 658

def validate_action(action)
  raise ArgumentError, "nil is not a valid action for resource #{self}" if action.nil?
end

#validate_resource_spec!(resource_spec) ⇒ Object



479
480
481
# File 'lib/chef/resource.rb', line 479

def validate_resource_spec!(resource_spec)
  run_context.resource_collection.validate_lookup_spec!(resource_spec)
end