Class: Chef::Resource
- Inherits:
-
Object
- Object
- Chef::Resource
- Extended by:
- Mixin::ConvertToClassName, Mixin::Provides
- Includes:
- DSL::DataQuery, DSL::PlatformIntrospection, DSL::RebootPending, DSL::RegistryHelper, Mixin::ConvertToClassName, Mixin::Deprecation, Mixin::PowershellOut, Mixin::Properties, Mixin::ShellOut
- Defined in:
- lib/chef/resource.rb,
lib/chef/resource/csh.rb,
lib/chef/resource/env.rb,
lib/chef/resource/git.rb,
lib/chef/resource/ksh.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/reboot.rb,
lib/chef/resource/script.rb,
lib/chef/resource/execute.rb,
lib/chef/resource/launchd.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/apt_update.rb,
lib/chef/resource/breakpoint.rb,
lib/chef/resource/dsc_script.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/osx_profile.rb,
lib/chef/resource/remote_file.rb,
lib/chef/resource/rpm_package.rb,
lib/chef/resource/yum_package.rb,
lib/chef/resource/action_class.rb,
lib/chef/resource/dpkg_package.rb,
lib/chef/resource/dsc_resource.rb,
lib/chef/resource/http_request.rb,
lib/chef/resource/registry_key.rb,
lib/chef/resource/cookbook_file.rb,
lib/chef/resource/macosx_service.rb,
lib/chef/resource/pacman_package.rb,
lib/chef/resource/windows_script.rb,
lib/chef/resource/zypper_package.rb,
lib/chef/resource/deploy_revision.rb,
lib/chef/resource/freebsd_package.rb,
lib/chef/resource/openbsd_package.rb,
lib/chef/resource/paludis_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/windows_service.rb,
lib/chef/resource/homebrew_package.rb,
lib/chef/resource/macports_package.rb,
lib/chef/resource/remote_directory.rb,
lib/chef/resource/file/verification.rb,
lib/chef/resource/powershell_script.rb,
lib/chef/resource/chocolatey_package.rb,
lib/chef/resource/timestamped_deploy.rb,
lib/chef/resource/easy_install_package.rb,
lib/chef/resource/resource_notification.rb,
lib/chef/resource/whyrun_safe_ruby_block.rb,
lib/chef/resource/conditional_action_not_nothing.rb
Direct Known Subclasses
AptUpdate, Breakpoint, Cron, Deploy, Directory, DscResource, DscScript, Env, ErlCall, Execute, File, Group, HttpRequest, Ifconfig, LWRPBase, Launchd, Link, Log, Mdadm, Mount, Ohai, OsxProfile, Package, Reboot, RegistryKey, Route, RubyBlock, Scm, Service, User
Defined Under Namespace
Modules: ActionClass Classes: AptPackage, AptUpdate, Bash, Batch, BffPackage, Breakpoint, ChefGem, ChocolateyPackage, Conditional, ConditionalActionNotNothing, CookbookFile, Cron, Csh, Deploy, DeployBranch, DeployRevision, Directory, DpkgPackage, DscResource, DscScript, EasyInstallPackage, Env, ErlCall, Execute, File, FreebsdPackage, GemPackage, Git, Group, HomebrewPackage, HttpRequest, Ifconfig, IpsPackage, Ksh, LWRPBase, Launchd, Link, Log, MacosxService, MacportsPackage, Mdadm, Mount, Notification, Ohai, OpenbsdPackage, OsxProfile, Package, PacmanPackage, PaludisPackage, Perl, PortagePackage, PowershellScript, Python, Reboot, RegistryKey, RemoteDirectory, RemoteFile, Route, RpmPackage, Ruby, RubyBlock, Scm, Script, Service, SmartosPackage, SolarisPackage, Subversion, Template, TimestampedDeploy, User, WhyrunSafeRubyBlock, WindowsPackage, WindowsScript, WindowsService, YumPackage, ZypperPackage
Constant Summary collapse
- FORBIDDEN_IVARS =
Internal Resource Interface (for Chef)
[:@run_context, :@not_if, :@only_if, :@enclosing_provider]
- HIDDEN_IVARS =
[:@allowed_actions, :@resource_name, :@source_line, :@run_context, :@name, :@not_if, :@only_if, :@elapsed_time, :@enclosing_provider]
- @@sorted_descendants =
This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.
Deprecated.We memoize a sorted version of descendants so that resource lookups don’t have to sort all the things, all the time. This was causing performance issues in test runs, and probably in real life as well.
nil
Constants included from Mixin::ShellOut
Mixin::ShellOut::DEPRECATED_OPTIONS
Instance Attribute Summary collapse
-
#allowed_actions(value = NOT_PASSED) ⇒ Array<Symbol>
The list of actions this Resource is allowed to have.
-
#cookbook_name ⇒ String
The cookbook this resource was declared in.
-
#declared_type ⇒ String
The actual name that was used to create this resource.
-
#default_guard_interpreter ⇒ Class, ...
readonly
The guard interpreter that will be used to process ‘only_if` and `not_if` statements by default.
-
#elapsed_time ⇒ Integer
readonly
The time it took (in seconds) to run the most recently-run action.
-
#enclosing_provider ⇒ Chef::Provider
The provider this resource was declared in (if it was declared in an LWRP).
-
#ignore_failure(arg = nil) ⇒ Object
(also: #epic_fail)
Whether to ignore failures.
-
#not_if_args ⇒ Object
readonly
??? TODO unreferenced.
-
#only_if_args ⇒ Object
readonly
??? TODO unreferenced.
-
#params ⇒ Object
XXX: this is required for definition params inside of the scope of a subresource to work correctly.
-
#recipe_name ⇒ String
The recipe this resource was declared in.
-
#resource_initializing ⇒ Object
private
If we are currently initializing the resource, this will be true.
-
#retries(arg = nil) ⇒ Integer
The number of times to retry this resource if it fails by throwing an exception while running an action.
-
#retry_delay(arg = nil) ⇒ Integer
The number of seconds to wait between retries.
-
#run_context ⇒ Chef::RunContext
where the context for the current Chef run is stored, including the node and the resource collection.
-
#sensitive(arg = nil) ⇒ Boolean
Whether to treat this resource’s data as sensitive.
-
#source_line ⇒ String
The source line where this resource was declared.
-
#updated ⇒ Boolean
Whether or not this resource was updated during an action.
Class Method Summary collapse
-
.action(action, &recipe_block) ⇒ Object
Define an action on this resource.
-
.action_class(&block) ⇒ Object
private
The action class is an automatic ‘Provider` created to handle actions declared by `action :x do …
-
.allowed_actions(*actions) ⇒ Array<Symbol>
The list of allowed actions for the resource.
- .allowed_actions=(value) ⇒ Object
-
.declare_action_class(&block) ⇒ Object
private
Ensure the action class actually gets created.
-
.default_action(action_name = NOT_PASSED) ⇒ Array<Symbol>
The action that will be run if no other action is specified.
- .default_action=(action_name) ⇒ Object
- .deprecated_constants ⇒ Object
-
.dsl_name ⇒ String
deprecated
Deprecated.
Use resource_name instead.
-
.identity_attr(name = nil) ⇒ Symbol
deprecated
Deprecated.
‘identity_property` should be used instead.
-
.identity_property(name = nil) ⇒ Symbol
Set the identity of this resource to a particular property.
- .inherited(child) ⇒ Object
- .json_create(o) ⇒ Object
-
.load_current_value(&load_block) ⇒ Object
Define a method to load up this resource’s properties with the current actual values.
-
.provider_base(arg = nil) ⇒ Module
deprecated
Deprecated.
Use ‘provides` on the provider, or `provider` on the resource, instead.
-
.provides(name, **options, &block) ⇒ Object
Mark this resource as providing particular DSL.
- .provides?(node, resource_name) ⇒ Boolean
- .register_deprecated_lwrp_class(resource_class, class_name) ⇒ Object private
-
.resource_for_node(short_name, node) ⇒ Object
Returns a resource based on a short_name and node.
-
.resource_matching_short_name(short_name) ⇒ Object
Returns the class with the given resource_name.
-
.resource_name(name = NOT_PASSED) ⇒ Symbol
The display name of this resource type, for printing purposes.
- .resource_name=(name) ⇒ Object
- .sorted_descendants ⇒ Object
-
.state_attrs(*names) ⇒ Array<Symbol>
deprecated
Deprecated.
Use state_properties.keys instead. Note that when you declare properties with ‘property`: properties are added to state_properties by default, and can be turned off with `desired_state: false`
“‘ruby property :x # part of desired state property :y, desired_state: false # not part of desired state “`
-
.use_automatic_resource_name ⇒ Object
Use the class name as the resource name.
Instance Method Summary collapse
-
#action(arg = nil) ⇒ Array[Symbol]
The action or actions that will be taken when this resource is run.
-
#action= ⇒ Array[Symbol]
The action or actions that will be taken when this resource is run.
-
#after_created ⇒ Object
A hook called after a resource is created.
-
#as_json(*a) ⇒ Object
as_json does most of the to_json heavy lifted.
- #before_notifications ⇒ Object
-
#cookbook_version ⇒ Object
The cookbook in which this Resource was defined (if any).
-
#current_value ⇒ Object
Get the current actual value of this resource.
-
#current_value_does_not_exist! ⇒ Object
Call this in ‘load_current_value` to indicate that the value does not exist and that `current_resource` should therefore be `nil`.
-
#custom_exception_message(e) ⇒ String
Preface an exception message with generic Resource information.
- #customize_exception(e) ⇒ Object
-
#declared_key ⇒ Object
We usually want to store and reference resources by their declared type and not the actual type that was looked up by the Resolver (IE, “package” becomes YumPackage class).
- #defined_at ⇒ Object
- #delayed_notifications ⇒ Object
- #events ⇒ Object
-
#guard_interpreter(arg = nil) ⇒ Class, ...
The guard interpreter that will be used to process ‘only_if` and `not_if` statements.
-
#identity ⇒ Object, Hash<Symbol,Object>
The value of the identity of this resource.
- #immediate_notifications ⇒ Object
-
#initialize(name, run_context = nil) ⇒ Resource
constructor
Create a new Resource.
- #inspect ⇒ Object
-
#is(*args) ⇒ Object
TODO Seems unused.
-
#load_from(resource) ⇒ Object
Make this resource into an exact (shallow) copy of the other resource.
- #lookup_provider_constant(name, action = :nothing) ⇒ Object private
-
#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.
-
#name ⇒ String
The name of this particular resource.
-
#node ⇒ Chef::Node
The node the current Chef run is using.
-
#noop(tf = nil) ⇒ Object
??? TODO Seems unused.
-
#not_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource.
-
#notifies(action, resource_spec, timing = :delayed) ⇒ Object
Sets up a notification that will run a particular action on another resource if and when this resource is updated by an action.
-
#notifies_before(action, resource_spec) ⇒ Object
Helper for #notifies.
-
#notifies_delayed(action, resource_spec) ⇒ Object
Helper for #notifies.
-
#notifies_immediately(action, resource_spec) ⇒ Object
Helper for #notifies.
-
#only_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource.
-
#provider(arg = nil) ⇒ Object
The provider class for this resource.
- #provider=(arg) ⇒ Object
- #provider_for_action(action) ⇒ Object
-
#resolve_notification_references ⇒ Object
Iterates over all immediate and delayed notifications, calling resolve_resource_reference on each in turn, causing them to resolve lazy/forward references.
-
#resource_name ⇒ Symbol
The display name of this resource type, for printing purposes.
-
#resources(*args) ⇒ Object
Find existing resources by searching the list of existing resources.
-
#run_action(action, notification_type = nil, notifying_resource = nil) ⇒ Object
Runs the given action on this resource, immediately.
-
#should_skip?(action) ⇒ Boolean
Evaluates not_if and only_if conditionals.
- #source_line_file ⇒ Object
- #source_line_number ⇒ Object
-
#state_for_resource_reporter ⇒ Hash{Symbol => Object}
(also: #state)
Get the value of the state attributes in this resource as a hash.
-
#subscribes(action, resources, timing = :delayed) ⇒ Object
Subscribes to updates from other resources, causing a particular action to run on this resource when the other resource is updated.
-
#supports(args = {}) ⇒ Object
Sets a list of capabilities of the real resource.
- #supports=(args) ⇒ Object
- #to_hash ⇒ Object
-
#to_json(*a) ⇒ Object
Serialize this object as a hash.
-
#to_s ⇒ Object
Generic Ruby and Data Structure Stuff (for user).
- #to_text ⇒ Object
-
#updated? ⇒ Boolean
Whether or not this resource was updated during an action.
-
#updated_by_last_action(true_or_false) ⇒ Boolean
Whether or not this resource was updated during the most recent action.
-
#updated_by_last_action? ⇒ Boolean
Whether or not this resource was updated during the most recent action.
- #validate_action(action) ⇒ Object
-
#validate_resource_spec!(resource_spec) ⇒ Object
Helper for #notifies.
Methods included from Mixin::Provides
provided_as, provides, provides?
Methods included from Mixin::DescendantsTracker
#descendants, descendants, direct_descendants, #direct_descendants, find_descendants_by_name, #find_descendants_by_name, #inherited, store_inherited
Methods included from Mixin::ConvertToClassName
constantize, convert_to_class_name, convert_to_snake_case, filename_to_qualified_string, normalize_snake_case_name, snake_case_basename
Methods included from Mixin::Deprecation
#deprecated_attr, #deprecated_attr_reader, #deprecated_attr_writer, #deprecated_ivar
Methods included from Mixin::Properties
included, #property_is_set?, #reset_property
Methods included from Mixin::ParamsValidate
#lazy, #set_or_return, #validate
Methods included from Mixin::PowershellOut
#powershell_out, #powershell_out!
Methods included from Mixin::WindowsArchitectureHelper
#assert_valid_windows_architecture!, #disable_wow64_file_redirection, #forced_32bit_override_required?, #is_i386_process_on_x86_64_windows?, #node_supports_windows_architecture?, #node_windows_architecture, #restore_wow64_file_redirection, #valid_windows_architecture?, #with_os_architecture, #wow64_architecture_override_required?, #wow64_directory
Methods included from Mixin::ShellOut
#run_command_compatible_options, #shell_out, #shell_out!, #shell_out_with_systems_locale, #shell_out_with_systems_locale!
Methods included from DSL::RebootPending
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 DSL::DataQuery
#data_bag, #data_bag_item, #search
Methods included from EncryptedDataBagItem::CheckEncrypted
Constructor Details
#initialize(name, run_context = nil) ⇒ Resource
Create a new Resource.
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
# File 'lib/chef/resource.rb', line 135 def initialize(name, run_context = nil) name(name) unless name.nil? @run_context = run_context @noop = nil @before = nil @params = Hash.new @provider = nil @allowed_actions = self.class.allowed_actions.to_a @action = self.class.default_action @updated = false @updated_by_last_action = false @supports = {} @ignore_failure = false @retries = 0 @retry_delay = 2 @not_if = [] @only_if = [] @source_line = nil # We would like to raise an error when the user gives us a guard # interpreter and a ruby_block to the guard. In order to achieve this # we need to understand when the user overrides the default guard # interpreter. Therefore we store the default separately in a different # attribute. @guard_interpreter = nil @default_guard_interpreter = :default @elapsed_time = 0 @sensitive = false 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.
1336 1337 1338 1339 1340 1341 1342 |
# File 'lib/chef/resource.rb', line 1336 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}' for #{self.class}" end end |
Instance Attribute Details
#allowed_actions(value = NOT_PASSED) ⇒ Array<Symbol>
The list of actions this Resource is allowed to have. Setting ‘action` will fail unless it is in this list. Default: [ :nothing ]
845 846 847 |
# File 'lib/chef/resource.rb', line 845 def allowed_actions @allowed_actions end |
#cookbook_name ⇒ String
Returns The cookbook this resource was declared in.
1241 1242 1243 |
# File 'lib/chef/resource.rb', line 1241 def cookbook_name @cookbook_name end |
#declared_type ⇒ String
The actual name that was used to create this resource. Sometimes, when you say something like ‘package ’blah’‘, the system will create a different resource (i.e. `YumPackage`). When this happens, the user will expect to see the thing they wrote, not the type that was returned. May be `nil`, in which case callers should read #resource_name. See #declared_key.
1265 1266 1267 |
# File 'lib/chef/resource.rb', line 1265 def declared_type @declared_type end |
#default_guard_interpreter ⇒ Class, ... (readonly)
The guard interpreter that will be used to process ‘only_if` and `not_if` statements by default. If left unset, or set to `:default`, the guard interpreter used will be Chef::GuardInterpreter::DefaultGuardInterpreter.
Must be a resource class like ‘Chef::Resource::Execute`, or a corresponding to the name of a resource. The resource must descend from `Chef::Resource::Execute`.
TODO this needs to be coerced on input so that retrieval is consistent.
836 837 838 |
# File 'lib/chef/resource.rb', line 836 def default_guard_interpreter @default_guard_interpreter end |
#elapsed_time ⇒ Integer (readonly)
The time it took (in seconds) to run the most recently-run action. Not cumulative across actions. This is set to 0 as soon as a new action starts running, and set to the elapsed time at the end of the action.
action. Not cumulative.
455 456 457 |
# File 'lib/chef/resource.rb', line 455 def elapsed_time @elapsed_time end |
#enclosing_provider ⇒ Chef::Provider
Returns The provider this resource was declared in (if it was declared in an LWRP). When you call methods that do not exist on this Resource, Chef will try to call the method on the provider as well before giving up.
1250 1251 1252 |
# File 'lib/chef/resource.rb', line 1250 def enclosing_provider @enclosing_provider end |
#ignore_failure(arg = nil) ⇒ Object Also known as: epic_fail
Whether to ignore failures. If set to ‘true`, and this resource when an action is run, the resource will be marked as failed but no exception will be thrown (and no error will be output). Defaults to `false`.
TODO ignore_failure and retries seem to be mutually exclusive; I doubt that was intended.
538 539 540 |
# File 'lib/chef/resource.rb', line 538 def ignore_failure(arg = nil) set_or_return(:ignore_failure, arg, kind_of: [ TrueClass, FalseClass ]) end |
#not_if_args ⇒ Object (readonly)
??? TODO unreferenced. Delete?
443 444 445 |
# File 'lib/chef/resource.rb', line 443 def not_if_args @not_if_args end |
#only_if_args ⇒ Object (readonly)
??? TODO unreferenced. Delete?
445 446 447 |
# File 'lib/chef/resource.rb', line 445 def only_if_args @only_if_args end |
#params ⇒ Object
XXX: this is required for definition params inside of the scope of a subresource to work correctly.
1233 1234 1235 |
# File 'lib/chef/resource.rb', line 1233 def params @params end |
#recipe_name ⇒ String
Returns The recipe this resource was declared in.
1244 1245 1246 |
# File 'lib/chef/resource.rb', line 1244 def recipe_name @recipe_name end |
#resource_initializing ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
If we are currently initializing the resource, this will be true.
Do NOT use this. It may be removed. It is for internal purposes only.
625 626 627 |
# File 'lib/chef/resource.rb', line 625 def resource_initializing @resource_initializing end |
#retries(arg = nil) ⇒ Integer
The number of times to retry this resource if it fails by throwing an exception while running an action. Default: 0
When the retries have run out, the Resource will throw the last exception.
414 415 416 |
# File 'lib/chef/resource.rb', line 414 def retries(arg = nil) set_or_return(:retries, arg, kind_of: Integer) end |
#retry_delay(arg = nil) ⇒ Integer
The number of seconds to wait between retries. Default: 2.
425 426 427 |
# File 'lib/chef/resource.rb', line 425 def retry_delay(arg = nil) set_or_return(:retry_delay, arg, kind_of: Integer) end |
#run_context ⇒ Chef::RunContext
where the context for the current Chef run is stored, including the node and the resource collection.
1238 1239 1240 |
# File 'lib/chef/resource.rb', line 1238 def run_context @run_context end |
#sensitive(arg = nil) ⇒ Boolean
Whether to treat this resource’s data as sensitive. If set, no resource data will be displayed in log output.
437 438 439 |
# File 'lib/chef/resource.rb', line 437 def sensitive(arg = nil) set_or_return(:sensitive, arg, :kind_of => [ TrueClass, FalseClass ]) end |
#source_line ⇒ String
Returns The source line where this resource was declared. Expected to come from caller() or a stack trace, it usually follows one of these formats:
/some/path/to/file.rb:80:in `wombat_tears'
C:/some/path/to/file.rb:80 in 1`wombat_tears'.
1257 1258 1259 |
# File 'lib/chef/resource.rb', line 1257 def source_line @source_line end |
#updated ⇒ Boolean
Whether or not this resource was updated during an action. If multiple actions are set on the resource, this will be ‘true` if any action caused an update to happen.
860 861 862 |
# File 'lib/chef/resource.rb', line 860 def updated @updated end |
Class Method Details
.action(action, &recipe_block) ⇒ Object
Define an action on this resource.
The action is defined as a recipe block that will be compiled and then converged when the action is taken (when Resource is converged). The recipe has access to the resource’s attributes and methods, as well as the Chef recipe DSL.
Resources in the action recipe may notify and subscribe to other resources within the action recipe, but cannot notify or subscribe to resources in the main Chef run.
Resource actions are inheritable: if resource A defines ‘action :create` and B is a subclass of A, B gets all of A’s actions. Additionally, resource B can define ‘action :create` and call `super()` to invoke A’s action code.
The first action defined (besides ‘:nothing`) will become the default action for the resource.
1125 1126 1127 1128 1129 1130 1131 |
# File 'lib/chef/resource.rb', line 1125 def self.action(action, &recipe_block) action = action.to_sym declare_action_class action_class.action(action, &recipe_block) self.allowed_actions += [ action ] default_action action if Array(default_action) == [:nothing] end |
.action_class(&block) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The action class is an automatic ‘Provider` created to handle actions declared by `action :x do … end`.
This class will be returned by ‘resource.provider` if `resource.provider` is not set. `provider_for_action` will also use this instead of calling out to `Chef::ProviderResolver`.
If the user has not declared actions on this class or its superclasses using ‘action :x do … end`, then there is no need for this class and `action_class` will be `nil`.
If a block is passed, the action_class is always created and the block is run inside it.
1188 1189 1190 1191 1192 1193 1194 1195 |
# File 'lib/chef/resource.rb', line 1188 def self.action_class(&block) return @action_class if @action_class && !block # If the superclass needed one, then we need one as well. if block || (superclass.respond_to?(:action_class) && superclass.action_class) @action_class = declare_action_class(&block) end @action_class end |
.allowed_actions(*actions) ⇒ Array<Symbol>
The list of allowed actions for the resource.
1049 1050 1051 1052 1053 1054 1055 1056 1057 |
# File 'lib/chef/resource.rb', line 1049 def self.allowed_actions(*actions) @allowed_actions ||= if superclass.respond_to?(:allowed_actions) superclass.allowed_actions.dup else [ :nothing ] end @allowed_actions |= actions.flatten end |
.allowed_actions=(value) ⇒ Object
1059 1060 1061 |
# File 'lib/chef/resource.rb', line 1059 def self.allowed_actions=(value) @allowed_actions = value.uniq end |
.declare_action_class(&block) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Ensure the action class actually gets created. This is called when the user does ‘action :x do … end`.
If a block is passed, it is run inside the action_class.
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 |
# File 'lib/chef/resource.rb', line 1204 def self.declare_action_class(&block) @action_class ||= begin if superclass.respond_to?(:action_class) base_provider = superclass.action_class end base_provider ||= Chef::Provider resource_class = self Class.new(base_provider) do include ActionClass self.resource_class = resource_class end end @action_class.class_eval(&block) if block @action_class end |
.default_action(action_name = NOT_PASSED) ⇒ Array<Symbol>
The action that will be run if no other action is specified.
Setting default_action will automatially add the action to allowed_actions, if it isn’t already there.
Defaults to [:nothing].
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 |
# File 'lib/chef/resource.rb', line 1076 def self.default_action(action_name = NOT_PASSED) unless action_name.equal?(NOT_PASSED) @default_action = Array(action_name).map(&:to_sym) self.allowed_actions |= @default_action end if @default_action @default_action elsif superclass.respond_to?(:default_action) superclass.default_action else [:nothing] end end |
.default_action=(action_name) ⇒ Object
1091 1092 1093 |
# File 'lib/chef/resource.rb', line 1091 def self.default_action=(action_name) default_action action_name end |
.deprecated_constants ⇒ Object
1550 1551 1552 |
# File 'lib/chef/resource.rb', line 1550 def self.deprecated_constants @deprecated_constants ||= {} end |
.dsl_name ⇒ String
Use resource_name instead.
The DSL name of this resource (e.g. ‘package` or `yum_package`)
958 959 960 961 962 963 964 |
# File 'lib/chef/resource.rb', line 958 def self.dsl_name Chef.log_deprecation "Resource.dsl_name is deprecated and will be removed in Chef 13. Use resource_name instead." if name name = self.name.split("::")[-1] convert_to_snake_case(name) end end |
.identity_attr(name = nil) ⇒ Symbol
‘identity_property` should be used instead.
Set a property as the “identity attribute” for this resource.
Identical to calling #identity_property.first.key.
817 818 819 820 821 |
# File 'lib/chef/resource.rb', line 817 def self.identity_attr(name = nil) property = identity_property(name) return nil if !property property.name end |
.identity_property(name = nil) ⇒ Symbol
Set the identity of this resource to a particular property.
This drives #identity, which returns data that uniquely refers to a given resource on the given node (in such a way that it can be correlated across Chef runs).
This method is unnecessary when declaring properties with ‘property`; properties can be added to identity during declaration with `identity: true`.
“‘ruby property :x, identity: true # part of identity property :y # not part of identity “`
795 796 797 798 799 800 801 |
# File 'lib/chef/resource.rb', line 795 def self.identity_property(name = nil) result = identity_properties(*Array(name)) if result.size > 1 raise Chef::Exceptions::MultipleIdentityError, "identity_property cannot be called on an object with more than one identity property (#{result.map { |r| r.name }.join(", ")})." end result.first end |
.inherited(child) ⇒ Object
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 |
# File 'lib/chef/resource.rb', line 1322 def self.inherited(child) super @@sorted_descendants = nil # set resource_name automatically if it's not set if child.name && !child.resource_name if child.name =~ /^Chef::Resource::(\w+)$/ child.resource_name(convert_to_snake_case($1)) end end end |
.json_create(o) ⇒ Object
702 703 704 705 706 707 708 |
# File 'lib/chef/resource.rb', line 702 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 |
.load_current_value(&load_block) ⇒ Object
Define a method to load up this resource’s properties with the current actual values.
1140 1141 1142 |
# File 'lib/chef/resource.rb', line 1140 def self.load_current_value(&load_block) define_method(:load_current_value!, &load_block) end |
.provider_base(arg = nil) ⇒ Module
Use ‘provides` on the provider, or `provider` on the resource, instead.
The module where Chef should look for providers for this resource. The provider for ‘MyResource` will be looked up using `provider_base::MyResource`. Defaults to `Chef::Provider`.
1035 1036 1037 1038 1039 1040 |
# File 'lib/chef/resource.rb', line 1035 def self.provider_base(arg = nil) if arg Chef.log_deprecation("Resource.provider_base is deprecated and will be removed in Chef 13. Use provides on the provider, or provider on the resource, instead.") end @provider_base ||= arg || Chef::Provider end |
.provides(name, **options, &block) ⇒ Object
Mark this resource as providing particular DSL.
Resources have an automatic DSL based on their resource_name, equivalent to ‘provides :resource_name` (providing the resource on all OS’s). If you declare a ‘provides` with the given resource_name, it replaces that provides (so that you can provide your resource DSL only on certain OS’s).
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 |
# File 'lib/chef/resource.rb', line 1352 def self.provides(name, **, &block) name = name.to_sym # `provides :resource_name, os: 'linux'`) needs to remove the old # canonical DSL before adding the new one. if @resource_name && name == @resource_name remove_canonical_dsl end result = Chef.resource_handler_map.set(name, self, , &block) Chef::DSL::Resources.add_resource_dsl(name) result end |
.provides?(node, resource_name) ⇒ Boolean
1366 1367 1368 |
# File 'lib/chef/resource.rb', line 1366 def self.provides?(node, resource_name) Chef::ResourceResolver.new(node, resource_name).provided_by?(self) end |
.register_deprecated_lwrp_class(resource_class, class_name) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 |
# File 'lib/chef/resource.rb', line 1538 def self.register_deprecated_lwrp_class(resource_class, class_name) if Chef::Resource.const_defined?(class_name, false) Chef::Log.warn "#{class_name} already exists! Deprecation class overwrites #{resource_class}" Chef::Resource.send(:remove_const, class_name) end if !Chef::Config[:treat_deprecation_warnings_as_errors] Chef::Resource.const_set(class_name, resource_class) deprecated_constants[class_name.to_sym] = resource_class end end |
.resource_for_node(short_name, node) ⇒ Object
Returns a resource based on a short_name and node
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
1518 1519 1520 1521 1522 |
# File 'lib/chef/resource.rb', line 1518 def self.resource_for_node(short_name, node) klass = Chef::ResourceResolver.resolve(short_name, node: node) raise Chef::Exceptions::NoSuchResourceType.new(short_name, node) if klass.nil? klass end |
.resource_matching_short_name(short_name) ⇒ Object
Returns the class with the given resource_name.
Parameters
- short_name<Symbol>
-
short_name of the resource (ie :directory)
Returns
- <Chef::Resource>
-
returns the proper Chef::Resource class
1533 1534 1535 |
# File 'lib/chef/resource.rb', line 1533 def self.resource_matching_short_name(short_name) Chef::ResourceResolver.resolve(short_name, canonical: true) end |
.resource_name(name = NOT_PASSED) ⇒ Symbol
The display name of this resource type, for printing purposes.
This also automatically calls “provides” to provide DSL with the given name.
resource_name defaults to your class name.
Call ‘resource_name nil` to remove the resource name (and any corresponding DSL).
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 |
# File 'lib/chef/resource.rb', line 982 def self.resource_name(name = NOT_PASSED) # Setter if name != NOT_PASSED remove_canonical_dsl # Set the resource_name and call provides if name name = name.to_sym # If our class is not already providing this name, provide it. if !Chef::ResourceResolver.includes_handler?(name, self) provides name, canonical: true end @resource_name = name else @resource_name = nil end end @resource_name end |
.resource_name=(name) ⇒ Object
1002 1003 1004 |
# File 'lib/chef/resource.rb', line 1002 def self.resource_name=(name) resource_name(name) end |
.sorted_descendants ⇒ Object
1318 1319 1320 |
# File 'lib/chef/resource.rb', line 1318 def self.sorted_descendants @@sorted_descendants ||= descendants.sort_by { |x| x.to_s } end |
.state_attrs(*names) ⇒ Array<Symbol>
Use state_properties.keys instead. Note that when you declare properties with ‘property`: properties are added to state_properties by default, and can be turned off with `desired_state: false`
“‘ruby property :x # part of desired state property :y, desired_state: false # not part of desired state “`
Set or return the list of “state properties” implemented by the Resource subclass.
Equivalent to calling #state_properties and getting ‘state_properties.keys`.
767 768 769 |
# File 'lib/chef/resource.rb', line 767 def self.state_attrs(*names) state_properties(*names).map { |property| property.name } end |
.use_automatic_resource_name ⇒ Object
Use the class name as the resource name.
Munges the last part of the class name from camel case to snake case, and sets the resource_name to that:
A::B::BlahDBlah -> blah_d_blah
1014 1015 1016 1017 |
# File 'lib/chef/resource.rb', line 1014 def self.use_automatic_resource_name automatic_name = convert_to_snake_case(self.name.split("::")[-1]) resource_name automatic_name end |
Instance Method Details
#action(arg = nil) ⇒ Array[Symbol]
The action or actions that will be taken when this resource is run.
170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/chef/resource.rb', line 170 def action(arg = nil) if arg arg = Array(arg).map(&:to_sym) arg.each do |action| validate( { action: action }, { action: { kind_of: Symbol, equal_to: allowed_actions } } ) end @action = arg else @action end end |
#action= ⇒ Array[Symbol]
The action or actions that will be taken when this resource is run. Alias for normal assigment syntax.
186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/chef/resource.rb', line 186 def action(arg = nil) if arg arg = Array(arg).map(&:to_sym) arg.each do |action| validate( { action: action }, { action: { kind_of: Symbol, equal_to: allowed_actions } } ) end @action = arg else @action end end |
#after_created ⇒ Object
A hook called after a resource is created. Meant to be overriden by subclasses.
947 948 949 |
# File 'lib/chef/resource.rb', line 947 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
669 670 671 672 673 674 675 676 677 678 679 |
# File 'lib/chef/resource.rb', line 669 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 |
#before_notifications ⇒ Object
1383 1384 1385 |
# File 'lib/chef/resource.rb', line 1383 def before_notifications run_context.before_notifications(self) end |
#cookbook_version ⇒ Object
The cookbook in which this Resource was defined (if any).
1430 1431 1432 1433 1434 |
# File 'lib/chef/resource.rb', line 1430 def cookbook_version if cookbook_name run_context.cookbook_collection[cookbook_name] end end |
#current_value ⇒ Object
Get the current actual value of this resource.
This does not cache–a new value will be returned each time.
1162 1163 1164 1165 1166 1167 1168 1169 |
# File 'lib/chef/resource.rb', line 1162 def current_value provider = provider_for_action(Array(action).first) if provider.whyrun_mode? && !provider.whyrun_supported? raise "Cannot retrieve #{self.class.current_resource} in why-run mode: #{provider} does not support why-run" end provider.load_current_resource provider.current_resource end |
#current_value_does_not_exist! ⇒ Object
Call this in ‘load_current_value` to indicate that the value does not exist and that `current_resource` should therefore be `nil`.
1150 1151 1152 |
# File 'lib/chef/resource.rb', line 1150 def current_value_does_not_exist! raise Chef::Exceptions::CurrentValueDoesNotExist end |
#custom_exception_message(e) ⇒ String
Preface an exception message with generic Resource information.
1475 1476 1477 |
# File 'lib/chef/resource.rb', line 1475 def (e) "#{self} (#{defined_at}) had an error: #{e.class.name}: #{e.}" end |
#customize_exception(e) ⇒ Object
1479 1480 1481 1482 1483 |
# File 'lib/chef/resource.rb', line 1479 def customize_exception(e) new_exception = e.exception((e)) new_exception.set_backtrace(e.backtrace) new_exception end |
#declared_key ⇒ Object
We usually want to store and reference resources by their declared type and not the actual type that was looked up by the Resolver (IE, “package” becomes YumPackage class). If we have not been provided the declared key we want to fall back on the old to_s key.
1378 1379 1380 1381 |
# File 'lib/chef/resource.rb', line 1378 def declared_key return to_s if declared_type.nil? "#{declared_type}[#{@name}]" end |
#defined_at ⇒ Object
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 |
# File 'lib/chef/resource.rb', line 1411 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. if cookbook_name && recipe_name && source_line "#{cookbook_name}::#{recipe_name} line #{source_line_number}" elsif source_line "#{source_line_file} line #{source_line_number}" else "dynamically defined" end end |
#delayed_notifications ⇒ Object
1391 1392 1393 |
# File 'lib/chef/resource.rb', line 1391 def delayed_notifications run_context.delayed_notifications(self) end |
#events ⇒ Object
1436 1437 1438 |
# File 'lib/chef/resource.rb', line 1436 def events run_context.events end |
#guard_interpreter(arg = nil) ⇒ Class, ...
The guard interpreter that will be used to process ‘only_if` and `not_if` statements. If left unset, the #default_guard_interpreter will be used.
Must be a resource class like ‘Chef::Resource::Execute`, or a corresponding to the name of a resource. The resource must descend from `Chef::Resource::Execute`.
TODO this needs to be coerced on input so that retrieval is consistent.
471 472 473 474 475 476 477 |
# File 'lib/chef/resource.rb', line 471 def guard_interpreter(arg = nil) if arg.nil? @guard_interpreter || @default_guard_interpreter else set_or_return(:guard_interpreter, arg, :kind_of => Symbol) end end |
#identity ⇒ Object, Hash<Symbol,Object>
The value of the identity of this resource.
-
If there are no identity properties on the resource, ‘name` is returned.
-
If there is exactly one identity property on the resource, it is returned.
-
If there are more than one, they are returned in a hash.
517 518 519 520 521 522 523 524 525 |
# File 'lib/chef/resource.rb', line 517 def identity result = {} identity_properties = self.class.identity_properties identity_properties.each do |property| result[property.name] = send(property.name) end return result.values.first if identity_properties.size == 1 result end |
#immediate_notifications ⇒ Object
1387 1388 1389 |
# File 'lib/chef/resource.rb', line 1387 def immediate_notifications run_context.immediate_notifications(self) end |
#inspect ⇒ Object
659 660 661 662 663 664 |
# File 'lib/chef/resource.rb', line 659 def inspect ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS ivars.inject("<#{self}") do |str, ivar| str << " #{ivar}: #{instance_variable_get(ivar).inspect}" end << ">" end |
#is(*args) ⇒ Object
TODO Seems unused. Delete?
1461 1462 1463 1464 1465 1466 1467 |
# File 'lib/chef/resource.rb', line 1461 def is(*args) if args.size == 1 args.first else return *args end end |
#load_from(resource) ⇒ Object
Make this resource into an exact (shallow) copy of the other resource.
553 554 555 556 557 558 559 |
# File 'lib/chef/resource.rb', line 553 def load_from(resource) resource.instance_variables.each do |iv| unless iv == :@source_line || iv == :@action || iv == :@not_if || iv == :@only_if self.instance_variable_set(iv, resource.instance_variable_get(iv)) end end end |
#lookup_provider_constant(name, action = :nothing) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 |
# File 'lib/chef/resource.rb', line 1555 def lookup_provider_constant(name, action = :nothing) begin self.class.provider_base.const_get(convert_to_class_name(name.to_s)) rescue NameError => e if e.to_s =~ /#{Regexp.escape(self.class.provider_base.to_s)}/ raise ArgumentError, "No provider found to match '#{name}'" else raise e end end end |
#name ⇒ String
The name of this particular resource.
This special resource attribute is set automatically from the declaration of the resource, e.g.
execute 'Vitruvius' do
command 'ls'
end
Will set the name to “Vitruvius”.
This is also used in to_s to show the resource name, e.g. ‘execute`.
This is also used for resource notifications and subscribes in the same manner.
This will coerce any object into a string via #to_s. Arrays are a special case so that ‘package [“foo”, “bar”]` becomes package[foo, bar] instead of the more awkward `package[[“foo”, “bar”]]` that #to_s would produce.
91 |
# File 'lib/chef/resource.rb', line 91 property :name, String, coerce: proc { |v| v.is_a?(Array) ? v.join(", ") : v.to_s }, desired_state: false |
#node ⇒ Chef::Node
The node the current Chef run is using.
Corresponds to ‘run_context.node`.
100 101 102 |
# File 'lib/chef/resource.rb', line 100 def node run_context && run_context.node end |
#noop(tf = nil) ⇒ Object
??? TODO Seems unused. Delete?
1452 1453 1454 1455 1456 1457 1458 |
# File 'lib/chef/resource.rb', line 1452 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
A command or block that indicates whether to actually run this resource. The command or block is run just before the action actually executes, and the action will be skipped if the block returns true.
If a block is specified, it must return ‘false` in order for the Resource to be executed.
If a command is specified, the resource’s #guard_interpreter will run the command and interpret the results according to ‘opts`. For example, the default `execute` resource will be treated as `false` if the command returns a non-zero exit code, and `true` if it returns 0. Thus, in the default case:
-
‘not_if “your command”` will perform the action only if `your command`
returns a non-zero code.
-
‘only_if “your command”, valid_exit_codes: [ 1, 2, 3 ]` will perform the action only if `your command` returns something other than 1, 2, or 3.
397 398 399 400 401 402 |
# File 'lib/chef/resource.rb', line 397 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 that will run a particular action on another resource if and when this resource is updated by an action.
If the action does not update this resource, the notification never triggers.
Only one resource may be specified per notification.
‘delayed` notifications will only ever happen once per resource, so if multiple resources all notify a single resource to perform the same action, the action will only happen once. However, if they ask for different actions, each action will happen once, in the order they were updated.
‘immediate` notifications will cause the action to be triggered once per notification, regardless of how many other resources have triggered the notification as well.
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/chef/resource.rb', line 243 def notifies(action, resource_spec, timing = :delayed) # when using old-style resources(:template => "/foo.txt") style, you # could end up with multiple resources. validate_resource_spec!(resource_spec) resources = [ resource_spec ].flatten resources.each do |resource| case timing.to_s when "delayed" notifies_delayed(action, resource) when "immediate", "immediately" notifies_immediately(action, resource) when "before" notifies_before(action, resource) else raise ArgumentError, "invalid timing: #{timing} for notifies(#{action}, #{resources.inspect}, #{timing}) resource #{self} "\ "Valid timings are: :delayed, :immediate, :immediately, :before" end end true end |
#notifies_before(action, resource_spec) ⇒ Object
Helper for #notifies
1284 1285 1286 |
# File 'lib/chef/resource.rb', line 1284 def notifies_before(action, resource_spec) run_context.notifies_before(Notification.new(resource_spec, action, self)) end |
#notifies_delayed(action, resource_spec) ⇒ Object
Helper for #notifies
1294 1295 1296 |
# File 'lib/chef/resource.rb', line 1294 def notifies_delayed(action, resource_spec) run_context.notifies_delayed(Notification.new(resource_spec, action, self)) end |
#notifies_immediately(action, resource_spec) ⇒ Object
Helper for #notifies
1289 1290 1291 |
# File 'lib/chef/resource.rb', line 1289 def notifies_immediately(action, resource_spec) run_context.notifies_immediately(Notification.new(resource_spec, action, self)) end |
#only_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource. The command or block is run just before the action actually executes, and the action will be skipped if the block returns false.
If a block is specified, it must return ‘true` in order for the Resource to be executed.
If a command is specified, the resource’s #guard_interpreter will run the command and interpret the results according to ‘opts`. For example, the default `execute` resource will be treated as `false` if the command returns a non-zero exit code, and `true` if it returns 0. Thus, in the default case:
-
‘only_if “your command”` will perform the action only if `your command`
returns 0.
-
‘only_if “your command”, valid_exit_codes: [ 1, 2, 3 ]` will perform the action only if `your command` returns 1, 2, or 3.
367 368 369 370 371 372 |
# File 'lib/chef/resource.rb', line 367 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(arg = nil) ⇒ Object
The provider class for this resource.
If ‘action :x do … end` has been declared on this resource or its superclasses, this will return the `action_class`.
If this is not set, ‘provider_for_action` will dynamically determine the provider.
733 734 735 736 737 738 739 740 741 |
# File 'lib/chef/resource.rb', line 733 def provider(arg = nil) klass = if arg.kind_of?(String) || arg.kind_of?(Symbol) lookup_provider_constant(arg) else arg end set_or_return(:provider, klass, kind_of: [ Class ]) || self.class.action_class end |
#provider=(arg) ⇒ Object
743 744 745 |
# File 'lib/chef/resource.rb', line 743 def provider=(arg) provider(arg) end |
#provider_for_action(action) ⇒ Object
1444 1445 1446 1447 1448 1449 |
# File 'lib/chef/resource.rb', line 1444 def provider_for_action(action) provider_class = Chef::ProviderResolver.new(node, self, action).resolve provider = provider_class.new(self, run_context) provider.action = action provider end |
#resolve_notification_references ⇒ Object
Iterates over all immediate and delayed notifications, calling resolve_resource_reference on each in turn, causing them to resolve lazy/forward references.
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
# File 'lib/chef/resource.rb', line 1271 def resolve_notification_references run_context.before_notifications(self).each { |n| n.resolve_resource_reference(run_context.resource_collection) } 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 |
#resource_name ⇒ Symbol
The display name of this resource type, for printing purposes.
Will be used to print out the resource in messages, e.g. resource_name
916 917 918 |
# File 'lib/chef/resource.rb', line 916 def resource_name @resource_name || self.class.resource_name end |
#resources(*args) ⇒ Object
Find existing resources by searching the list of existing resources. Possible forms are:
find(:file => "foobar")
find(:file => [ "foobar", "baz" ])
find("file[foobar]", "file[baz]")
find("file[foobar,baz]")
Calls ‘run_context.resource_collection.find(*args)`
120 121 122 |
# File 'lib/chef/resource.rb', line 120 def resources(*args) run_context.resource_collection.find(*args) end |
#run_action(action, notification_type = nil, notifying_resource = nil) ⇒ Object
Runs the given action on this resource, immediately.
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/chef/resource.rb', line 570 def run_action(action, notification_type = nil, = 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, ) # 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) # Don't modify @retries directly and keep it intact, so that the # recipe_snippet from ResourceFailureInspector can print the value # that was set in the resource block initially. remaining_retries = retries begin return if should_skip?(action) provider_for_action(action).run_action rescue Exception => e if ignore_failure Chef::Log.error("#{(e)}; ignore_failure is set, continuing") events.resource_failed(self, action, e) elsif remaining_retries > 0 events.resource_failed_retriable(self, action, remaining_retries, e) remaining_retries -= 1 Chef::Log.info("Retrying execution of #{self}, #{remaining_retries} attempt(s) left") sleep retry_delay retry else events.resource_failed(self, action, e) raise customize_exception(e) end end ensure @elapsed_time = Time.now - start_time # Reporting endpoint doesn't accept a negative resource duration so set it to 0. # A negative value can occur when a resource changes the system time backwards @elapsed_time = 0 if @elapsed_time < 0 events.resource_completed(self) 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
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 |
# File 'lib/chef/resource.rb', line 1495 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 |
#source_line_file ⇒ Object
1395 1396 1397 1398 1399 1400 1401 |
# File 'lib/chef/resource.rb', line 1395 def source_line_file if source_line source_line.match(/(.*):(\d+):?.*$/).to_a[1] else nil end end |
#source_line_number ⇒ Object
1403 1404 1405 1406 1407 1408 1409 |
# File 'lib/chef/resource.rb', line 1403 def source_line_number if source_line source_line.match(/(.*):(\d+):?.*$/).to_a[2] else nil end end |
#state_for_resource_reporter ⇒ Hash{Symbol => Object} Also known as: state
Get the value of the state attributes in this resource as a hash.
Does not include properties that are not set (unless they are identity properties).
488 489 490 491 492 493 494 495 496 497 |
# File 'lib/chef/resource.rb', line 488 def state_for_resource_reporter state = {} state_properties = self.class.state_properties state_properties.each do |property| if property.identity? || property.is_set?(self) state[property.name] = send(property.name) end end state end |
#subscribes(action, resources, timing = :delayed) ⇒ Object
Subscribes to updates from other resources, causing a particular action to run on this resource when the other resource is updated.
If multiple resources are specified, this resource action will be run if any of them change.
This notification will only trigger once, no matter how many other resources are updated (or how many actions are run by a particular resource).
330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/chef/resource.rb', line 330 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
Sets a list of capabilities of the real resource. For example, ‘:remount` (for filesystems) and `:restart` (for services).
TODO Calling resource.supports({}) will not set this to empty; it will do a get instead. That’s wrong.
931 932 933 934 935 936 937 |
# File 'lib/chef/resource.rb', line 931 def supports(args = {}) if args.any? @supports = args else @supports end end |
#supports=(args) ⇒ Object
939 940 941 |
# File 'lib/chef/resource.rb', line 939 def supports=(args) supports(args) end |
#to_hash ⇒ Object
687 688 689 690 691 692 693 694 695 696 697 698 699 700 |
# File 'lib/chef/resource.rb', line 687 def to_hash # Grab all current state, then any other ivars (backcompat) result = {} self.class.state_properties.each do |p| result[p.name] = p.get(self) end safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS safe_ivars.each do |iv| key = iv.to_s.sub(/^@/, "").to_sym next if result.has_key?(key) result[key] = instance_variable_get(iv) end result end |
#to_json(*a) ⇒ Object
Serialize this object as a hash
682 683 684 685 |
# File 'lib/chef/resource.rb', line 682 def to_json(*a) results = as_json Chef::JSONCompat.to_json(results, *a) end |
#to_s ⇒ Object
Generic Ruby and Data Structure Stuff (for user)
638 639 640 |
# File 'lib/chef/resource.rb', line 638 def to_s "#{resource_name}[#{name}]" end |
#to_text ⇒ Object
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
# File 'lib/chef/resource.rb', line 642 def to_text return "suppressed sensitive resource output" if sensitive ivars = instance_variables.map { |ivar| ivar.to_sym } - HIDDEN_IVARS text = "# Declared in #{@source_line}\n\n" text << "#{resource_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
Whether or not this resource was updated during an action. If multiple actions are set on the resource, this will be ‘true` if any action caused an update to happen.
869 870 871 |
# File 'lib/chef/resource.rb', line 869 def updated? updated end |
#updated_by_last_action(true_or_false) ⇒ Boolean
Whether or not this resource was updated during the most recent action. This is set to ‘false` at the beginning of each action.
881 882 883 884 |
# File 'lib/chef/resource.rb', line 881 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
Whether or not this resource was updated during the most recent action. This is set to ‘false` at the beginning of each action.
892 893 894 |
# File 'lib/chef/resource.rb', line 892 def updated_by_last_action? @updated_by_last_action end |
#validate_action(action) ⇒ Object
1440 1441 1442 |
# File 'lib/chef/resource.rb', line 1440 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
Helper for #notifies
1371 1372 1373 |
# File 'lib/chef/resource.rb', line 1371 def validate_resource_spec!(resource_spec) run_context.resource_collection.validate_lookup_spec!(resource_spec) end |