Class: Chef::Resource

Inherits:
Object
  • Object
show all
Extended by:
DSL::Universal, Mixin::ConvertToClassName, Mixin::Provides
Includes:
DSL::DeclareResource, DSL::RebootPending, DSL::Universal, Mixin::ConvertToClassName, Mixin::Deprecation, Mixin::Properties
Defined in:
lib/chef/resource.rb,
lib/chef/resource/csh.rb,
lib/chef/resource/ksh.rb,
lib/chef/resource/log.rb,
lib/chef/resource/bash.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/sudo.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/plist.rb,
lib/chef/resource/route.rb,
lib/chef/resource/locale.rb,
lib/chef/resource/python.rb,
lib/chef/resource/reboot.rb,
lib/chef/resource/script.rb,
lib/chef/resource/sysctl.rb,
lib/chef/resource/execute.rb,
lib/chef/resource/launchd.rb,
lib/chef/resource/package.rb,
lib/chef/resource/scm/git.rb,
lib/chef/resource/service.rb,
lib/chef/resource/chef_gem.rb,
lib/chef/resource/hostname.rb,
lib/chef/resource/ifconfig.rb,
lib/chef/resource/template.rb,
lib/chef/resource/timezone.rb,
lib/chef/resource/cron/cron.rb,
lib/chef/resource/directory.rb,
lib/chef/resource/lwrp_base.rb,
lib/chef/resource/macos_pkg.rb,
lib/chef/resource/ohai_hint.rb,
lib/chef/resource/rhsm_repo.rb,
lib/chef/resource/swap_file.rb,
lib/chef/resource/apt_update.rb,
lib/chef/resource/breakpoint.rb,
lib/chef/resource/chef_sleep.rb,
lib/chef/resource/dsc_script.rb,
lib/chef/resource/ruby_block.rb,
lib/chef/resource/apt_package.rb,
lib/chef/resource/bff_package.rb,
lib/chef/resource/cab_package.rb,
lib/chef/resource/conditional.rb,
lib/chef/resource/cron/cron_d.rb,
lib/chef/resource/cron_access.rb,
lib/chef/resource/dmg_package.rb,
lib/chef/resource/dnf_package.rb,
lib/chef/resource/gem_package.rb,
lib/chef/resource/ips_package.rb,
lib/chef/resource/msu_package.rb,
lib/chef/resource/osx_profile.rb,
lib/chef/resource/remote_file.rb,
lib/chef/resource/rhsm_errata.rb,
lib/chef/resource/rpm_package.rb,
lib/chef/resource/user_ulimit.rb,
lib/chef/resource/windows_env.rb,
lib/chef/resource/windows_uac.rb,
lib/chef/resource/yum_package.rb,
lib/chef/resource/action_class.rb,
lib/chef/resource/alternatives.rb,
lib/chef/resource/archive_file.rb,
lib/chef/resource/chef_handler.rb,
lib/chef/resource/dpkg_package.rb,
lib/chef/resource/dsc_resource.rb,
lib/chef/resource/homebrew_tap.rb,
lib/chef/resource/http_request.rb,
lib/chef/resource/inspec_input.rb,
lib/chef/resource/notify_group.rb,
lib/chef/resource/registry_key.rb,
lib/chef/resource/selinux_port.rb,
lib/chef/resource/selinux_user.rb,
lib/chef/resource/snap_package.rb,
lib/chef/resource/systemd_unit.rb,
lib/chef/resource/user/pw_user.rb,
lib/chef/resource/windows_font.rb,
lib/chef/resource/windows_path.rb,
lib/chef/resource/windows_task.rb,
lib/chef/resource/cookbook_file.rb,
lib/chef/resource/homebrew_cask.rb,
lib/chef/resource/inspec_waiver.rb,
lib/chef/resource/kernel_module.rb,
lib/chef/resource/rhsm_register.rb,
lib/chef/resource/selinux_login.rb,
lib/chef/resource/selinux_state.rb,
lib/chef/resource/user/aix_user.rb,
lib/chef/resource/user/mac_user.rb,
lib/chef/resource/windows_share.rb,
lib/chef/resource/apt_preference.rb,
lib/chef/resource/apt_repository.rb,
lib/chef/resource/habitat_config.rb,
lib/chef/resource/macosx_service.rb,
lib/chef/resource/pacman_package.rb,
lib/chef/resource/scm/subversion.rb,
lib/chef/resource/selinux_module.rb,
lib/chef/resource/windows_script.rb,
lib/chef/resource/yum_repository.rb,
lib/chef/resource/zypper_package.rb,
lib/chef/resource/build_essential.rb,
lib/chef/resource/freebsd_package.rb,
lib/chef/resource/habitat_install.rb,
lib/chef/resource/habitat_service.rb,
lib/chef/resource/homebrew_update.rb,
lib/chef/resource/openbsd_package.rb,
lib/chef/resource/openssl_dhparam.rb,
lib/chef/resource/paludis_package.rb,
lib/chef/resource/portage_package.rb,
lib/chef/resource/selinux_boolean.rb,
lib/chef/resource/selinux_install.rb,
lib/chef/resource/smartos_package.rb,
lib/chef/resource/solaris_package.rb,
lib/chef/resource/user/linux_user.rb,
lib/chef/resource/windows_ad_join.rb,
lib/chef/resource/windows_feature.rb,
lib/chef/resource/windows_package.rb,
lib/chef/resource/windows_printer.rb,
lib/chef/resource/windows_service.rb,
lib/chef/resource/chef_client_cron.rb,
lib/chef/resource/homebrew_package.rb,
lib/chef/resource/macports_package.rb,
lib/chef/resource/openssl_x509_crl.rb,
lib/chef/resource/remote_directory.rb,
lib/chef/resource/selinux_fcontext.rb,
lib/chef/resource/windows_auto_run.rb,
lib/chef/resource/windows_defender.rb,
lib/chef/resource/windows_dns_zone.rb,
lib/chef/resource/windows_pagefile.rb,
lib/chef/resource/windows_shortcut.rb,
lib/chef/resource/chef_vault_secret.rb,
lib/chef/resource/chocolatey_config.rb,
lib/chef/resource/chocolatey_source.rb,
lib/chef/resource/file/verification.rb,
lib/chef/resource/habitat_user_toml.rb,
lib/chef/resource/powershell_script.rb,
lib/chef/resource/rhsm_errata_level.rb,
lib/chef/resource/rhsm_subscription.rb,
lib/chef/resource/user/solaris_user.rb,
lib/chef/resource/user/windows_user.rb,
lib/chef/resource/windows_workgroup.rb,
lib/chef/resource/zypper_repository.rb,
lib/chef/resource/chef_client_config.rb,
lib/chef/resource/chocolatey_feature.rb,
lib/chef/resource/chocolatey_package.rb,
lib/chef/resource/macos_userdefaults.rb,
lib/chef/resource/powershell_package.rb,
lib/chef/resource/selinux_permissive.rb,
lib/chef/resource/windows_dfs_folder.rb,
lib/chef/resource/windows_dfs_server.rb,
lib/chef/resource/windows_dns_record.rb,
lib/chef/resource/chef_client_launchd.rb,
lib/chef/resource/habitat/habitat_sup.rb,
lib/chef/resource/windows_certificate.rb,
lib/chef/resource/chocolatey_installer.rb,
lib/chef/resource/openssl_x509_request.rb,
lib/chef/resource/windows_audit_policy.rb,
lib/chef/resource/windows_feature_dism.rb,
lib/chef/resource/windows_printer_port.rb,
lib/chef/resource/openssl_ec_public_key.rb,
lib/chef/resource/resource_notification.rb,
lib/chef/resource/ssh_known_hosts_entry.rb,
lib/chef/resource/windows_dfs_namespace.rb,
lib/chef/resource/windows_firewall_rule.rb,
lib/chef/resource/file/verification/json.rb,
lib/chef/resource/file/verification/yaml.rb,
lib/chef/resource/openssl_ec_private_key.rb,
lib/chef/resource/openssl_rsa_public_key.rb,
lib/chef/resource/whyrun_safe_ruby_block.rb,
lib/chef/resource/windows_user_privilege.rb,
lib/chef/resource/habitat/habitat_package.rb,
lib/chef/resource/openssl_rsa_private_key.rb,
lib/chef/resource/windows_security_policy.rb,
lib/chef/resource/windows_update_settings.rb,
lib/chef/resource/inspec_waiver_file_entry.rb,
lib/chef/resource/openssl_x509_certificate.rb,
lib/chef/resource/windows_firewall_profile.rb,
lib/chef/resource/chef_client_systemd_timer.rb,
lib/chef/resource/powershell_package_source.rb,
lib/chef/resource/chef_client_scheduled_task.rb,
lib/chef/resource/windows_defender_exclusion.rb,
lib/chef/resource/windows_feature_powershell.rb,
lib/chef/resource/habitat/habitat_sup_systemd.rb,
lib/chef/resource/habitat/habitat_sup_windows.rb,
lib/chef/resource/conditional_action_not_nothing.rb,
lib/chef/resource/file/verification/systemd_unit.rb,
lib/chef/resource/chef_client_trusted_certificate.rb

Direct Known Subclasses

Alternatives, AptPreference, AptRepository, AptUpdate, ArchiveFile, Breakpoint, BuildEssential, ChefClientConfig, ChefClientCron, ChefClientLaunchd, ChefClientScheduledTask, ChefClientSystemdTimer, ChefClientTrustedCertificate, ChefHandler, ChefSleep, ChefVaultSecret, ChocolateyConfig, ChocolateyFeature, ChocolateyInstaller, ChocolateySource, Cron, CronAccess, CronD, Directory, DmgPackage, DscResource, DscScript, Execute, File, Git, Group, HabitatConfig, HabitatInstall, HabitatService, HabitatSup, HabitatUserToml, HomebrewCask, HomebrewTap, HomebrewUpdate, Hostname, HttpRequest, Ifconfig, InspecInput, InspecWaiver, InspecWaiverFileEntry, KernelModule, LWRPBase, Launchd, Link, Locale, Log, MacosPkg, MacosUserDefaults, Mdadm, Mount, NotifyGroup, Ohai, OhaiHint, OpensslDhparam, OpensslEcPrivateKey, OpensslEcPublicKey, OpensslRsaPrivateKey, OpensslRsaPublicKey, OpensslX509Certificate, OpensslX509Crl, OpensslX509Request, OsxProfile, Package, PlistResource, PowershellPackageSource, Reboot, RegistryKey, RhsmErrata, RhsmErrataLevel, RhsmRegister, RhsmRepo, RhsmSubscription, Route, RubyBlock, SelinuxBoolean, SelinuxFcontext, SelinuxInstall, SelinuxLogin, SelinuxModule, SelinuxPermissive, SelinuxPort, SelinuxState, SelinuxUser, Service, SshKnownHostsEntry, Subversion, Sudo, SwapFile, Sysctl, SystemdUnit, Timezone, UnresolvedSubscribes, User, UserUlimit, WindowsAdJoin, WindowsAuditPolicy, WindowsAutorun, WindowsCertificate, WindowsDefender, WindowsDefenderExclusion, WindowsDfsFolder, WindowsDfsNamespace, WindowsDfsServer, WindowsDnsRecord, WindowsDnsZone, WindowsEnv, WindowsFeature, WindowsFeatureDism, WindowsFeaturePowershell, WindowsFirewallProfile, WindowsFirewallRule, WindowsFont, WindowsPagefile, WindowsPath, WindowsPrinter, WindowsPrinterPort, WindowsSecurityPolicy, WindowsShare, WindowsShortcut, WindowsTask, WindowsUac, WindowsUpdateSettings, WindowsUserPrivilege, WindowsWorkgroup, YumRepository, ZypperRepository

Defined Under Namespace

Classes: ActionClass, Alternatives, AptPackage, AptPreference, AptRepository, AptUpdate, ArchiveFile, Bash, Batch, BffPackage, Breakpoint, BuildEssential, CabPackage, ChefClientConfig, ChefClientCron, ChefClientLaunchd, ChefClientScheduledTask, ChefClientSystemdTimer, ChefClientTrustedCertificate, ChefGem, ChefHandler, ChefSleep, ChefVaultSecret, ChocolateyConfig, ChocolateyFeature, ChocolateyInstaller, ChocolateyPackage, ChocolateySource, Conditional, ConditionalActionNotNothing, CookbookFile, Cron, CronAccess, CronD, Csh, Directory, DmgPackage, DnfPackage, DpkgPackage, DscResource, DscScript, Execute, File, FreebsdPackage, GemPackage, Git, Group, HabitatConfig, HabitatInstall, HabitatPackage, HabitatService, HabitatSup, HabitatSupSystemd, HabitatSupWindows, HabitatUserToml, HomebrewCask, HomebrewPackage, HomebrewTap, HomebrewUpdate, Hostname, HttpRequest, Ifconfig, InspecInput, InspecWaiver, InspecWaiverFileEntry, IpsPackage, KernelModule, Ksh, LWRPBase, Launchd, Link, Locale, Log, MacosPkg, MacosUserDefaults, MacosxService, MacportsPackage, Mdadm, Mount, MsuPackage, Notification, NotifyGroup, Ohai, OhaiHint, OpenbsdPackage, OpensslDhparam, OpensslEcPrivateKey, OpensslEcPublicKey, OpensslRsaPrivateKey, OpensslRsaPublicKey, OpensslX509Certificate, OpensslX509Crl, OpensslX509Request, OsxProfile, Package, PacmanPackage, PaludisPackage, Perl, PlistResource, PortagePackage, PowershellPackage, PowershellPackageSource, PowershellScript, Python, Reboot, RegistryKey, RemoteDirectory, RemoteFile, RhsmErrata, RhsmErrataLevel, RhsmRegister, RhsmRepo, RhsmSubscription, Route, RpmPackage, Ruby, RubyBlock, Script, SelinuxBoolean, SelinuxFcontext, SelinuxInstall, SelinuxLogin, SelinuxModule, SelinuxPermissive, SelinuxPort, SelinuxState, SelinuxUser, Service, SmartosPackage, SnapPackage, SolarisPackage, SshKnownHostsEntry, Subversion, Sudo, SwapFile, Sysctl, SystemdUnit, Template, Timezone, UnresolvedSubscribes, User, UserUlimit, WhyrunSafeRubyBlock, WindowsAdJoin, WindowsAuditPolicy, WindowsAutorun, WindowsCertificate, WindowsDefender, WindowsDefenderExclusion, WindowsDfsFolder, WindowsDfsNamespace, WindowsDfsServer, WindowsDnsRecord, WindowsDnsZone, WindowsEnv, WindowsFeature, WindowsFeatureDism, WindowsFeaturePowershell, WindowsFirewallProfile, WindowsFirewallRule, WindowsFont, WindowsPackage, WindowsPagefile, WindowsPath, WindowsPrinter, WindowsPrinterPort, WindowsScript, WindowsSecurityPolicy, WindowsService, WindowsShare, WindowsShortcut, WindowsTask, WindowsUac, WindowsUpdateSettings, WindowsUserPrivilege, WindowsWorkgroup, YumPackage, YumRepository, ZypperPackage, ZypperRepository

Constant Summary collapse

FORBIDDEN_IVARS =

FORBIDDEN_IVARS do not show up when the resource is converted to JSON (ie. hidden from data_collector and sending to the chef server via #to_json/to_h/as_json/inspect)

%i{@run_context @logger @not_if @only_if @enclosing_provider @description @introduced @examples @validation_message @deprecated @default_description @target_mode @skip_docs @executed_by_runner @action_descriptions}.freeze
HIDDEN_IVARS =

HIDDEN_IVARS do not show up when the resource is displayed to the user as text (ie. in the error inspector output via #to_text)

%i{@allowed_actions @resource_name @source_line @run_context @logger @name @not_if @only_if @elapsed_time @enclosing_provider @description @introduced @examples @validation_message @deprecated @default_description @target_mode @skip_docs @executed_by_runner @action_descriptions}.freeze
@@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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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::LazyModuleInclude

#descendants, #include, #included

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 DSL::Secret

#default_secret_config, #default_secret_service, #secret, #with_secret_config, #with_secret_service

Methods included from DSL::RenderHelpers

#render_json, #render_toml, #render_yaml

Methods included from DSL::ReaderHelpers

#parse_file, #parse_json, #parse_toml, #parse_yaml

Methods included from DSL::Powershell

#ps_credential

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::ChefVault

#chef_vault, #chef_vault_item, #chef_vault_item_for_environment

Methods included from DSL::DataQuery

#data_bag, #data_bag_item, #search, #tagged?

Methods included from EncryptedDataBagItem::CheckEncrypted

#encrypted?

Methods included from DSL::PlatformIntrospection

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

Methods included from Mixin::ConvertToClassName

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

#copy_properties_from, included, #property_description, #property_is_set?, #reset_property

Methods included from Mixin::ParamsValidate

#lazy, #set_or_return, #validate

Methods included from DSL::RebootPending

#reboot_pending?

Methods included from DSL::DeclareResource

#build_resource, #declare_resource, #delete_resource, #delete_resource!, #edit_resource, #edit_resource!, #find_resource, #find_resource!, #resources, #with_run_context

Constructor Details

#initialize(name, run_context = nil) ⇒ Resource

Create a new Resource.

Parameters:

  • name

    The name of this resource (corresponds to the #name attribute, used for notifications to this resource).

  • run_context (defaults to: nil)

    The context of the Chef run. Corresponds to #run_context.



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/chef/resource.rb', line 111

def initialize(name, run_context = nil)
  name(name) unless name.nil?
  @run_context = run_context

  @logger = if run_context
              run_context.logger.with_child({ name: name, resource: resource_name })
            else
              Chef::Log.with_child({ name: name, resource: resource_name })
            end

  @before = nil
  @params = {}
  @provider = nil
  @allowed_actions = self.class.allowed_actions.to_a
  @action = self.class.default_action
  @updated = false
  @updated_by_last_action = false
  @not_if = []
  @only_if = []
  @source_line = nil
  @deprecated = false
  @skip_docs = false
  # 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
  @executed_by_runner = 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.



1341
1342
1343
1344
1345
1346
1347
# File 'lib/chef/resource.rb', line 1341

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) ⇒ Object



892
893
894
895
896
897
# File 'lib/chef/resource.rb', line 892

def allowed_actions(value = NOT_PASSED)
  if value != NOT_PASSED
    self.allowed_actions = value
  end
  @allowed_actions
end

#cookbook_nameString

Returns The cookbook this resource was declared in.

Returns:

  • (String)

    The cookbook this resource was declared in.



1246
1247
1248
# File 'lib/chef/resource.rb', line 1246

def cookbook_name
  @cookbook_name
end

#declared_typeString

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.

Returns:

  • (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.



1274
1275
1276
# File 'lib/chef/resource.rb', line 1274

def declared_type
  @declared_type
end

#default_guard_interpreterClass, ... (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.

Returns:

  • (Class, Symbol, String)

    the default Guard interpreter resource.



881
882
883
# File 'lib/chef/resource.rb', line 881

def default_guard_interpreter
  @default_guard_interpreter
end

#elapsed_timeInteger (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.

Returns:

  • (Integer)

    The time (in seconds) it took to process the most recent



470
471
472
# File 'lib/chef/resource.rb', line 470

def elapsed_time
  @elapsed_time
end

#enclosing_providerChef::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.

Returns:

  • (Chef::Provider)

    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.



1257
1258
1259
# File 'lib/chef/resource.rb', line 1257

def enclosing_provider
  @enclosing_provider
end

#executed_by_runnerBoolean

Returns If the resource was executed by the runner.

Returns:

  • (Boolean)

    If the resource was executed by the runner



474
475
476
# File 'lib/chef/resource.rb', line 474

def executed_by_runner
  @executed_by_runner
end

#loggerMixlib::Log::Child (readonly)

of the run context's logger, if one exists.

Returns:

  • (Mixlib::Log::Child)

    The logger for this resources. This is a child



1242
1243
1244
# File 'lib/chef/resource.rb', line 1242

def logger
  @logger
end

#paramsObject

XXX: this is required for definition params inside of the scope of a subresource to work correctly.



1231
1232
1233
# File 'lib/chef/resource.rb', line 1231

def params
  @params
end

#recipe_nameString

Returns The recipe this resource was declared in.

Returns:

  • (String)

    The recipe this resource was declared in.



1250
1251
1252
# File 'lib/chef/resource.rb', line 1250

def recipe_name
  @recipe_name
end

#resource_initializingObject

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.



639
640
641
# File 'lib/chef/resource.rb', line 639

def resource_initializing
  @resource_initializing
end

#run_contextChef::RunContext

where the context for the current Chef run is stored, including the node and the resource collection.

Returns:



1237
1238
1239
# File 'lib/chef/resource.rb', line 1237

def run_context
  @run_context
end

#source_lineString

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 1wombat_tears'.

Returns:

  • (String)

    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 1wombat_tears'



1265
1266
1267
# File 'lib/chef/resource.rb', line 1265

def source_line
  @source_line
end

#updatedBoolean (readonly)

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.

Returns:

  • (Boolean)

    Whether the resource was updated during an action.



906
907
908
# File 'lib/chef/resource.rb', line 906

def updated
  @updated
end

Class Method Details

.action(action, description: nil, &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.

Parameters:

  • name (Symbol)

    The action name to define.

  • description (String) (defaults to: nil)

    optional description for the action. Used for documentation generation.

  • recipe_block

    The recipe to run when the action is taken. This block takes no parameters, and will be evaluated in a new context containing:

    • The resource's public and protected methods (including attributes)
    • The Chef Recipe DSL (file, etc.)
    • super() referring to the parent version of the action (if any)

Returns:

  • The Action class implementing the action



1079
1080
1081
1082
1083
1084
1085
# File 'lib/chef/resource.rb', line 1079

def self.action(action, description: nil, &recipe_block)
  action = action.to_sym
  declare_action_class
  action_class.action(action, description: description, &recipe_block)
  self.allowed_actions += [ action ]
  default_action action if Array(default_action) == [:nothing]
end

.action_class(&block) ⇒ Object

The action class is a Chef::Provider which is created at Resource class evaluation time when the Custom Resource is being constructed.

This happens the first time the ruby parser hits an action or an action_class method, the presence of either indicates that this is going to be a Chef-12.5 custom resource. If we never see one of these directives then we are constructing an old-style Resource+Provider or LWRP or whatever.

If a block is passed, the action_class is always created and the block is run inside it.



1153
1154
1155
1156
1157
# File 'lib/chef/resource.rb', line 1153

def self.action_class(&block)
  @action_class ||= declare_action_class
  @action_class.class_eval(&block) if block
  @action_class
end

.allowed_actions(*actions) ⇒ Array<Symbol>

The list of allowed actions for the resource.

Parameters:

  • actions (Array<Symbol>)

    The list of actions to add to allowed_actions.

Returns:

  • (Array<Symbol>)

    The list of actions, as symbols.



1002
1003
1004
1005
1006
1007
1008
1009
1010
# File 'lib/chef/resource.rb', line 1002

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



1012
1013
1014
# File 'lib/chef/resource.rb', line 1012

def self.allowed_actions=(value)
  @allowed_actions = value.uniq
end

.chef_version_for_provides(constraint = NOT_PASSED) ⇒ Object

This API can be used for backcompat to do:

chef_version_for_provides "< 14.0" if defined?(:chef_version_for_provides)

For core chef versions that do not support chef_version: in provides lines.

Since resource_name calls provides the generally correct way of doing this is to do chef_version_for_provides first, then resource_name and then any additional options provides lines.

Once we no longer care about supporting chef < 14.4 then we can deprecate this API.

Parameters:

  • arg (String)

    version constraint to match against (e.g. "> 14")



1364
1365
1366
1367
# File 'lib/chef/resource.rb', line 1364

def self.chef_version_for_provides(constraint = NOT_PASSED)
  @chef_version_for_provides = constraint unless constraint == NOT_PASSED
  @chef_version_for_provides ||= nil
end

.custom_resource?Boolean

Returns true or false based on if the resource is a custom resource. The top-level Chef::Resource is not a chef resource. This value is inherited.

Returns:

  • (Boolean)

    if the resource is a custom_resource



1163
1164
1165
# File 'lib/chef/resource.rb', line 1163

def self.custom_resource?
  false
end

.declare_action_classObject

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.



1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
# File 'lib/chef/resource.rb', line 1183

def self.declare_action_class
  @action_class ||=
    begin
      is_custom_resource!
      base_provider =
        if superclass.custom_resource?
          superclass.action_class
        else

          ActionClass
        end

      resource_class = self
      Class.new(base_provider) do
        self.resource_class = resource_class
      end
    end
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 automatically add the action to allowed_actions, if it isn't already there.

Defaults to [:nothing].

Parameters:

  • action_name (Symbol, Array<Symbol>) (defaults to: NOT_PASSED)

    The default action (or series of actions) to use.

Returns:

  • (Array<Symbol>)

    The default actions for the resource.



1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/chef/resource.rb', line 1029

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 defined?(@default_action) && @default_action
    @default_action
  elsif superclass.respond_to?(:default_action)
    superclass.default_action
  else
    [:nothing]
  end
end

.default_action=(action_name) ⇒ Object



1044
1045
1046
# File 'lib/chef/resource.rb', line 1044

def self.default_action=(action_name)
  default_action action_name
end

.default_description(default_description = "NOT_PASSED") ⇒ Object



1487
1488
1489
1490
1491
1492
# File 'lib/chef/resource.rb', line 1487

def self.default_description(default_description = "NOT_PASSED")
  if default_description != "NOT_PASSED"
    @default_description = default_description
  end
  @default_description
end

.deprecated(deprecated = "NOT_PASSED") ⇒ Object



1472
1473
1474
1475
1476
1477
1478
# File 'lib/chef/resource.rb', line 1472

def self.deprecated(deprecated = "NOT_PASSED")
  if deprecated != "NOT_PASSED"
    @deprecated = true
    @deprecated_message = deprecated
  end
  @deprecated
end

.description(description = "NOT_PASSED") ⇒ Object



1451
1452
1453
1454
1455
1456
# File 'lib/chef/resource.rb', line 1451

def self.description(description = "NOT_PASSED")
  if description != "NOT_PASSED"
    @description = description
  end
  @description
end

.examples(examples = "NOT_PASSED") ⇒ Object



1465
1466
1467
1468
1469
1470
# File 'lib/chef/resource.rb', line 1465

def self.examples(examples = "NOT_PASSED")
  if examples != "NOT_PASSED"
    @examples = examples
  end
  @examples
end

.from_hash(o) ⇒ Object



738
739
740
741
742
743
744
# File 'lib/chef/resource.rb', line 738

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

.from_json(j) ⇒ Object



750
751
752
# File 'lib/chef/resource.rb', line 750

def self.from_json(j)
  from_hash(Chef::JSONCompat.parse(j))
end

.identity_attr(name = nil) ⇒ Symbol

Deprecated.

identity_property should be used instead.

Set a property as the "identity attribute" for this resource.

Identical to calling #identity_property.first.key.

Parameters:

  • name (Symbol) (defaults to: nil)

    The name of the property to set.

Returns:

Raises:

  • (ArgumentError)

    If no arguments are passed and the resource has more than one identity property.



861
862
863
864
865
866
# File 'lib/chef/resource.rb', line 861

def self.identity_attr(name = nil)
  property = identity_property(name)
  return nil unless 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.

property :x, identity: true # part of identity
property :y # not part of identity

Parameters:

  • name (Symbol) (defaults to: nil)

    A list of property names to set as the identity.

Returns:

  • (Symbol)

    The identity property if there is only one; or nil if there are more than one.

Raises:

  • (ArgumentError)

    If no arguments are passed and the resource has more than one identity property.



838
839
840
841
842
843
844
845
# File 'lib/chef/resource.rb', line 838

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(&:name).join(", ")})."
  end

  result.first
end

.inherited(child) ⇒ Object



1333
1334
1335
1336
# File 'lib/chef/resource.rb', line 1333

def self.inherited(child)
  super
  @@sorted_descendants = nil
end

.introduced(introduced = "NOT_PASSED") ⇒ Object



1458
1459
1460
1461
1462
1463
# File 'lib/chef/resource.rb', line 1458

def self.introduced(introduced = "NOT_PASSED")
  if introduced != "NOT_PASSED"
    @introduced = introduced
  end
  @introduced
end

.is_custom_resource!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.

This sets the resource to being a custom resource, and does so in a way that automatically inherits to all subclasses via defining a method on the class (class variables and class instance variables don't have the correct semantics here, this is a poor man's activesupport class_attribute)



1173
1174
1175
1176
1177
# File 'lib/chef/resource.rb', line 1173

def self.is_custom_resource!
  define_singleton_method :custom_resource? do
    true
  end
end

.json_create(o) ⇒ Object



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

def self.json_create(o)
  from_hash(o)
end

.load_current_value(&load_block) ⇒ Object

Define a method to load up this resource's properties with the current actual values.

Parameters:

  • load_block

    The block to load. Will be run in the context of a newly created resource with its identity values filled in.



1110
1111
1112
# File 'lib/chef/resource.rb', line 1110

def self.load_current_value(&load_block)
  define_method(:load_current_value!, &load_block)
end

.preview_resource(value = nil) ⇒ Boolean

Set or return if this resource is in preview mode.

This only has value in the resource_inspector to mark a resource as being new-to-chef-core. Its meaning is probably more equivalent to "experimental" in that the API might change even in minor versions due to bugfixing and is NOT considered "stable" yet.

Parameters:

  • value (nil, Boolean) (defaults to: nil)

    If nil, get the current value. If not nil, set the value of the flag.

Returns:

  • (Boolean)


1211
1212
1213
1214
1215
# File 'lib/chef/resource.rb', line 1211

def self.preview_resource(value = nil)
  @preview_resource = false unless defined?(@preview_resource)
  @preview_resource = value unless value.nil?
  @preview_resource
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).



1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
# File 'lib/chef/resource.rb', line 1376

def self.provides(name, **options, &block)
  name = name.to_sym

  # deliberately do not go through the accessor here
  @resource_name = name if resource_name.nil?

  if chef_version_for_provides && !options.include?(:chef_version)
    options[:chef_version] = chef_version_for_provides
  end

  result = Chef.resource_handler_map.set(name, self, **options, &block)
  Chef::DSL::Resources.add_resource_dsl(name)
  result
end

.provides?(node, resource_name) ⇒ Boolean

Returns:

  • (Boolean)


1391
1392
1393
# File 'lib/chef/resource.rb', line 1391

def self.provides?(node, resource_name)
  Chef::ResourceResolver.new(node, resource_name).provided_by?(self)
end

.resource_for_node(short_name, node) ⇒ Object

Returns a resource based on a short_name and node

==== Parameters short_name:: short_name of the resource (ie :directory) nodeChef::Node:: Node object to look up platform and version in

=== Returns Chef::Resource:: returns the proper Chef::Resource class



1607
1608
1609
1610
1611
1612
# File 'lib/chef/resource.rb', line 1607

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.

NOTE: Chef::Resource.resource_matching_short_name(:package) returns Chef::Resource::Package, while on rhel the API call Chef::Resource.resource_for_node(:package, node) will return Chef::Resource::YumPackage -- which is probably what you really want. This API should most likely be removed or changed to call resource_for_node.

==== Parameters short_name:: short_name of the resource (ie :directory)

=== Returns Chef::Resource:: returns the proper Chef::Resource class



1629
1630
1631
# File 'lib/chef/resource.rb', line 1629

def self.resource_matching_short_name(short_name)
  Chef::ResourceResolver.resolve(short_name)
end

.resource_name(name = NOT_PASSED) ⇒ Symbol

The display name of this resource type, for printing purposes.

Call resource_name nil to remove the resource name

Parameters:

  • value (Symbol)

    The desired name of this resource type (e.g. execute), or nil if this class is abstract and has no resource_name.

Returns:

  • (Symbol)

    The name of this resource type (e.g. :execute).



971
972
973
974
975
976
977
978
979
# File 'lib/chef/resource.rb', line 971

def self.resource_name(name = NOT_PASSED)
  # Setter
  if name != NOT_PASSED
    @resource_name = name.to_sym rescue nil
  end

  @resource_name = nil unless defined?(@resource_name)
  @resource_name
end

.resource_name=(name) ⇒ Object



981
982
983
# File 'lib/chef/resource.rb', line 981

def self.resource_name=(name)
  resource_name(name)
end

.skip_docs(skip_docs = "NOT_PASSED") ⇒ Object



1480
1481
1482
1483
1484
1485
# File 'lib/chef/resource.rb', line 1480

def self.skip_docs(skip_docs = "NOT_PASSED")
  if skip_docs != "NOT_PASSED"
    @skip_docs = skip_docs
  end
  @skip_docs
end

.sorted_descendantsObject



1329
1330
1331
# File 'lib/chef/resource.rb', line 1329

def self.sorted_descendants
  @@sorted_descendants ||= descendants.sort_by(&:to_s)
end

.state_attrs(*names) ⇒ Array<Symbol>

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

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.

Parameters:

  • names (Array<Symbol>)

    A list of property names to set as desired state.

Returns:

  • (Array<Symbol>)

    All property names with desired state.



810
811
812
# File 'lib/chef/resource.rb', line 810

def self.state_attrs(*names)
  state_properties(*names).map(&:name)
end

.target_mode(target_mode = "NOT_PASSED") ⇒ Object

Documentation-only keyword



1495
1496
1497
1498
1499
1500
# File 'lib/chef/resource.rb', line 1495

def self.target_mode(target_mode = "NOT_PASSED")
  if target_mode != "NOT_PASSED"
    @target_mode = target_mode
  end
  @target_mode
end

.unified_mode(flag = nil) ⇒ Boolean

If the resource's action should run in separated compile/converge mode.

Parameters:

  • flag (Boolean) (defaults to: nil)

    value to set unified_mode to

Returns:

  • (Boolean)

    unified_mode value



989
990
991
992
993
# File 'lib/chef/resource.rb', line 989

def self.unified_mode(flag = nil)
  @unified_mode = Chef::Config[:resource_unified_mode_default] if !defined?(@unified_mode) || @unified_mode.nil?
  @unified_mode = flag unless flag.nil?
  !!@unified_mode
end

.use(partial) ⇒ Object

Use a partial code fragment. This can be used for code sharing between multiple resources.

Do not wrap the code fragment in a class or module. It also does not support the use of super to subclass any methods defined in the fragment, the methods will just be overwritten.

Parameters:

  • partial (String)

    the code fragment to eval against the class



1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
# File 'lib/chef/resource.rb', line 1509

def self.use(partial)
  if partial =~ /^core::(.*)/
    partial = $1
    dirname = ::File.dirname(partial)
    basename = ::File.basename(partial, ".rb")
    basename = basename[1..] if basename.start_with?("_")
    class_eval IO.read(::File.expand_path("resource/#{dirname}/_#{basename}.rb", __dir__))
  else
    dirname = ::File.dirname(partial)
    basename = ::File.basename(partial, ".rb")
    basename = basename[1..] if basename.start_with?("_")

    # Support recursive `use`
    callers = caller_locations
    used_from = if callers.first.label == "use"
                  callers.detect { |caller| caller.label == "class_from_file" }.path
                else
                  callers.first.path
                end

    fullpath = ::File.expand_path("#{dirname}/_#{basename}.rb", ::File.dirname(used_from))
    class_eval IO.read(fullpath)
  end
end

Instance Method Details

#action(arg = nil) ⇒ Array[Symbol]

The action or actions that will be taken when this resource is run.

Parameters:

  • arg (Array[Symbol], Symbol) (defaults to: nil)

    A list of actions (e.g. :create)

Returns:

  • (Array[Symbol])

    the list of actions.



150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/chef/resource.rb', line 150

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 assignment syntax.

Parameters:

  • arg (Array[Symbol], Symbol)

    A list of actions (e.g. :create)

Returns:

  • (Array[Symbol])

    the list of actions.



166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/chef/resource.rb', line 166

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_description(action) ⇒ Object

Retrieve the description for a resource's action, if any description has been included in the definition.

was defined

Parameters:

Returns:

  • the description of the action provided, or nil if no description



1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
# File 'lib/chef/resource.rb', line 1093

def action_description(action)
  provider_for_action(action).class.action_description(action)
rescue Chef::Exceptions::ProviderNotFound
  # If a provider can't be found, there can be no description defined on the provider.
  nil
rescue NameError => e
  # This can happen when attempting to load a provider in a platform-specific
  # environment where we have not required the necessary files yet
  raise unless /uninitialized constant/.match?(e.message)
end

#after_createdObject

A hook called after a resource is created. Meant to be overridden by subclasses.



957
958
959
# File 'lib/chef/resource.rb', line 957

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



702
703
704
705
706
707
708
709
710
711
712
# File 'lib/chef/resource.rb', line 702

def as_json(*a)
  safe_ivars = instance_variables.map(&:to_sym) - FORBIDDEN_IVARS
  instance_vars = {}
  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_notificationsObject



1409
1410
1411
# File 'lib/chef/resource.rb', line 1409

def before_notifications
  run_context.before_notifications(self)
end

#compile_timeBoolean

If this is set the resource will be set to run at compile time and the converge time action will be set to :nothing.

Parameters:

  • arg (Boolean)

    Whether or not to force this resource to run at compile time.

Returns:

  • (Boolean)

    Whether or not to force this resource to run at compile time.



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

property :compile_time, [TrueClass, FalseClass],
description: "Determines whether or not the resource is executed during the compile time phase.",
default: false, desired_state: false

#cookbook_versionObject

The cookbook in which this Resource was defined (if any).

Returns:

  • Chef::CookbookVersion The cookbook in which this Resource was defined.



1538
1539
1540
1541
1542
# File 'lib/chef/resource.rb', line 1538

def cookbook_version
  if cookbook_name && cookbook_name != "@recipe_files"
    run_context.cookbook_collection[cookbook_name]
  end
end

#current_valueObject

Get the current actual value of this resource.

This does not cache--a new value will be returned each time.

Returns:

  • A new copy of the resource, with values filled in from the actual current value.



1130
1131
1132
1133
1134
1135
1136
1137
1138
# File 'lib/chef/resource.rb', line 1130

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.

Raises:

  • Chef::Exceptions::CurrentValueDoesNotExist



1119
1120
1121
# File 'lib/chef/resource.rb', line 1119

def current_value_does_not_exist!
  raise Chef::Exceptions::CurrentValueDoesNotExist
end

#custom_exception_message(e) ⇒ String

Preface an exception message with generic Resource information.

Parameters:

  • e (StandardError)

    An exception with e.message

Returns:

  • (String)

    An exception message customized with class name.



1564
1565
1566
# File 'lib/chef/resource.rb', line 1564

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

#customize_exception(e) ⇒ Object



1568
1569
1570
1571
1572
# File 'lib/chef/resource.rb', line 1568

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

#declared_keyObject

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.



1403
1404
1405
1406
1407
# File 'lib/chef/resource.rb', line 1403

def declared_key
  return to_s if declared_type.nil?

  "#{declared_type}[#{@name}]"
end

#defined_atObject



1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
# File 'lib/chef/resource.rb', line 1437

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_action(arg) ⇒ Object

Force a delayed notification into this resource's run_context.

This should most likely be paired with action :nothing

Parameters:

  • arg (Array[Symbol], Symbol)

    A list of actions (e.g. :create)



175
176
177
178
179
180
181
182
183
184
185
# File 'lib/chef/resource.rb', line 175

def delayed_action(arg)
  arg = Array(arg).map(&:to_sym)
  arg.map do |action|
    validate(
      { action: action },
      { action: { kind_of: Symbol, equal_to: allowed_actions } }
    )
    # the resource effectively sends a delayed notification to itself
    run_context.add_delayed_action(Notification.new(self, action, self, run_context.unified_mode))
  end
end

#delayed_notificationsObject



1417
1418
1419
# File 'lib/chef/resource.rb', line 1417

def delayed_notifications
  run_context.delayed_notifications(self)
end

#eventsObject



1544
1545
1546
# File 'lib/chef/resource.rb', line 1544

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.

Parameters:

  • arg (Class, Symbol, String) (defaults to: nil)

    The Guard interpreter resource class/ symbol/name.

Returns:

  • (Class, Symbol, String)

    The Guard interpreter resource.



489
490
491
492
493
494
495
# File 'lib/chef/resource.rb', line 489

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

#identityObject, 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.

Returns:

  • (Object, Hash<Symbol,Object>)

    The identity of this resource.



526
527
528
529
530
531
532
533
534
535
# File 'lib/chef/resource.rb', line 526

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

#ignore_failureObject

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. If set to :quiet or 'quiet', the normal error trace will be suppressed.

TODO ignore_failure and retries seem to be mutually exclusive; I doubt that was intended.

Parameters:

  • arg (Boolean, String, Symbol)

    Whether to ignore failures.

Returns:

  • Whether this resource will ignore failures.



549
# File 'lib/chef/resource.rb', line 549

property :ignore_failure, [ true, false, :quiet, "quiet" ], default: false, desired_state: false

#immediate_notificationsObject



1413
1414
1415
# File 'lib/chef/resource.rb', line 1413

def immediate_notifications
  run_context.immediate_notifications(self)
end

#inspectObject



692
693
694
695
696
697
# File 'lib/chef/resource.rb', line 692

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

#load_from(resource) ⇒ Object

Make this resource into an exact (shallow) copy of the other resource.

Parameters:



556
557
558
559
560
561
562
# File 'lib/chef/resource.rb', line 556

def load_from(resource)
  resource.instance_variables.each do |iv|
    unless iv == :@source_line || iv == :@action || iv == :@not_if || iv == :@only_if
      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.



1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
# File 'lib/chef/resource.rb', line 1634

def lookup_provider_constant(name, action = :nothing)
  # XXX: "name" is probably a poor choice of name here, ideally this would be nil, but we need to
  # fix resources so that nil or empty names work (also solving the apt_update "doesn't matter one bit"
  # problem).  WARNING: this string is not a public API and should not be referenced (e.g. in provides blocks)
  # and may change at any time.  If you've found this comment you're also probably very lost and should maybe
  # consider using `declare_resource :whatever` instead of trying to set `provider :whatever` on a resource, or in some
  # other way reconsider what you're trying to do, since you're likely trying to force a bad design that we
  # can't/won't support.
  self.class.resource_for_node(name, node).new("name", run_context).provider_for_action(action).class
end

#nameString

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[Vitruvius].

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.

Parameters:

  • name (Object)

    The name to set, typically a String or Array

Returns:

  • (String)

    The name of this Resource.



87
# File 'lib/chef/resource.rb', line 87

property :name, String, coerce: proc { |v| v.is_a?(Array) ? v.join(", ") : v.to_s }, desired_state: false, required: true

#nodeChef::Node

The node the current Chef run is using.

Corresponds to run_context.node.

Returns:

  • (Chef::Node)

    The node the current Chef run is using.



96
97
98
# File 'lib/chef/resource.rb', line 96

def node
  run_context && run_context.node
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.

Parameters:

  • command (String) (defaults to: nil)

    A string to execute.

  • opts (Hash) (defaults to: {})

    Options control the execution of the command

  • block (Proc)

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



409
410
411
412
413
414
# File 'lib/chef/resource.rb', line 409

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.

Examples:

Resource by string

file '/foo.txt' do
  content 'hi'
  notifies :create, 'file[/bar.txt]'
end
file '/bar.txt' do
  action :nothing
  content 'hi'
end

Resource by hash

file '/foo.txt' do
  content 'hi'
  notifies :create, file: '/bar.txt'
end
file '/bar.txt' do
  action :nothing
  content 'hi'
end

Direct Resource

bar = file '/bar.txt' do
  action :nothing
  content 'hi'
end
file '/foo.txt' do
  content 'hi'
  notifies :create, bar
end

Parameters:

  • action

    The action to run on the other resource.

  • resource_spec (String, Hash, Chef::Resource)

    The resource to run.

  • timing (String, Symbol) (defaults to: :delayed)

    When to notify. Has these values:

    • delayed: Will run the action on the other resource after all other actions have been run. This is the default.
    • immediate, immediately: Will run the action on the other resource immediately (before any other action is run).
    • before: Will run the action on the other resource immediately before the action is actually run.


242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/chef/resource.rb', line 242

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



1295
1296
1297
# File 'lib/chef/resource.rb', line 1295

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

#notifies_delayed(action, resource_spec) ⇒ Object

Helper for #notifies



1305
1306
1307
# File 'lib/chef/resource.rb', line 1305

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

#notifies_immediately(action, resource_spec) ⇒ Object

Helper for #notifies



1300
1301
1302
# File 'lib/chef/resource.rb', line 1300

def notifies_immediately(action, resource_spec)
  run_context.notifies_immediately(Notification.new(resource_spec, action, self, run_context.unified_mode))
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.

Parameters:

  • command (String) (defaults to: nil)

    A string to execute.

  • opts (Hash) (defaults to: {})

    Options control the execution of the command

  • block (Proc)

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



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

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.

Parameters:

  • arg (String, Symbol, Class) (defaults to: nil)

    Sets the provider class for this resource. If passed a String or Symbol, e.g. :file or "file", looks up the provider based on the name.

Returns:

  • The provider class for this resource.

See Also:



777
778
779
780
781
782
783
784
# File 'lib/chef/resource.rb', line 777

def provider(arg = nil)
  klass = if arg.is_a?(String) || arg.is_a?(Symbol)
            lookup_provider_constant(arg)
          else
            arg
          end
  set_or_return(:provider, klass, kind_of: [ Class ])
end

#provider=(arg) ⇒ Object



786
787
788
# File 'lib/chef/resource.rb', line 786

def provider=(arg)
  provider(arg)
end

#provider_for_action(action) ⇒ Object



1552
1553
1554
1555
1556
1557
# File 'lib/chef/resource.rb', line 1552

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(always_raise = false) ⇒ Object

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



1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
# File 'lib/chef/resource.rb', line 1280

def resolve_notification_references(always_raise = false)
  run_context.before_notifications(self).each do |n|
    n.resolve_resource_reference(run_context.resource_collection, true)
  end

  run_context.immediate_notifications(self).each do |n|
    n.resolve_resource_reference(run_context.resource_collection, always_raise)
  end

  run_context.delayed_notifications(self).each do |n|
    n.resolve_resource_reference(run_context.resource_collection, always_raise)
  end
end

#resource_nameSymbol

The display name of this resource type, for printing purposes.

Will be used to print out the resource in messages, e.g. resource_name[name]

Returns:

  • (Symbol)

    The name of this resource type (e.g. :execute).



949
950
951
# File 'lib/chef/resource.rb', line 949

def resource_name
  @resource_name || self.class.resource_name
end

#retriesInteger

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.

Parameters:

  • arg (Integer)

    The number of retries.

Returns:

  • (Integer)

    The number of retries.



425
# File 'lib/chef/resource.rb', line 425

property :retries, Integer, default: 0, desired_state: false

#retry_delayInteger

The number of seconds to wait between retries. Default: 2.

Parameters:

  • arg (Integer)

    The number of seconds to wait between retries.

Returns:

  • (Integer)

    The number of seconds to wait between retries.



432
# File 'lib/chef/resource.rb', line 432

property :retry_delay, Integer, default: 2, desired_state: false

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

Runs the given action on this resource, immediately.

Parameters:

  • action

    The action to run (e.g. :create)

  • notification_type (defaults to: nil)

    The notification type that triggered this (if any)

  • notifying_resource (defaults to: nil)

    The resource that triggered this notification (if any)

Raises:

  • Any error that occurs during the actual action.



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
619
620
621
622
623
624
625
# File 'lib/chef/resource.rb', line 573

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] || logger.level == :debug
    # This can be noisy
    logger.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)

    with_umask do
      provider_for_action(action).run_action
    end
  rescue StandardError => e
    if ignore_failure
      logger.error("#{custom_exception_message(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
      logger.info("Retrying execution of #{self}, #{remaining_retries} attempt#{"s" if remaining_retries > 1} 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

#sensitiveBoolean

Whether to treat this resource's data as sensitive. If set, no resource data will be displayed in log output.

Parameters:

  • arg (Boolean)

    Whether this resource is sensitive or not.

Returns:

  • (Boolean)

    Whether this resource is sensitive or not.



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

property :sensitive, [ TrueClass, FalseClass ], default: false, desired_state: false

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


1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
# File 'lib/chef/resource.rb', line 1584

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)
      logger.debug("Skipping #{self} due to #{conditional.description}")
      true
    end
  end
end

#source_line_fileObject



1421
1422
1423
1424
1425
1426
1427
# File 'lib/chef/resource.rb', line 1421

def source_line_file
  if source_line
    source_line.match(/(.*):(\d+):?.*$/).to_a[1]
  else
    nil
  end
end

#source_line_numberObject



1429
1430
1431
1432
1433
1434
1435
# File 'lib/chef/resource.rb', line 1429

def source_line_number
  if source_line
    source_line.match(/(.*):(\d+):?.*$/).to_a[2]
  else
    nil
  end
end

#state_for_resource_reporterHash{Symbol => Object}

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).

Returns:

  • (Hash{Symbol => Object})

    A Hash of attribute => value for the Resource class's state_attrs.



506
507
508
509
510
511
512
513
514
515
# File 'lib/chef/resource.rb', line 506

def state_for_resource_reporter
  state = {}
  state_properties = self.class.state_properties
  state_properties.each do |property|
    if property.is_set?(self)
      state[property.name] = property.sensitive? ? "*sensitive value suppressed*" : 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).

Examples:

Resources by string

file '/foo.txt' do
  content 'hi'
  action :nothing
  subscribes :create, 'file[/bar.txt]'
end
file '/bar.txt' do
  content 'hi'
end

Direct resource

bar = file '/bar.txt' do
  content 'hi'
end
file '/foo.txt' do
  content 'hi'
  action :nothing
  subscribes :create, bar
end

Multiple resources by string

file '/foo.txt' do
  content 'hi'
  action :nothing
  subscribes :create, [ 'file[/bar.txt]', 'file[/baz.txt]' ]
end
file '/bar.txt' do
  content 'hi'
end
file '/baz.txt' do
  content 'hi'
end

Multiple resources

bar = file '/bar.txt' do
  content 'hi'
end
baz = file '/bar.txt' do
  content 'hi'
end
file '/foo.txt' do
  content 'hi'
  action :nothing
  subscribes :create, [ bar, baz ]
end

Parameters:

  • action

    The action to run on the other resource.

  • resources (String, Resource, Array[String, Resource])

    The resources to subscribe to.

  • timing (String, Symbol) (defaults to: :delayed)

    When to notify. Has these values:

    • delayed: An update will cause the action to run after all other actions have been run. This is the default.
    • immediate, immediately: The action will run immediately following the other resource being updated.
    • before: The action will run immediately before the other resource is updated.


341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/chef/resource.rb', line 341

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

#suppress_up_to_date_messages?Boolean

This is used to suppress the "(up to date)" message in the doc formatter for the log resource (where it is nonsensical).

This is not exactly a private API, but its doubtful there exist many other sane use cases for this.

Returns:

  • (Boolean)


1651
1652
1653
# File 'lib/chef/resource.rb', line 1651

def suppress_up_to_date_messages?
  false
end

#to_hObject Also known as: to_hash



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/chef/resource.rb', line 720

def to_h
  # 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(&:to_sym) - FORBIDDEN_IVARS
  safe_ivars.each do |iv|
    key = iv.to_s.sub(/^@/, "").to_sym
    next if result.key?(key)

    result[key] = instance_variable_get(iv)
  end
  result
end

#to_json(*a) ⇒ Object

Serialize this object as a hash



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

def to_json(*a)
  results = as_json
  Chef::JSONCompat.to_json(results, *a)
end

#to_sObject

Generic Ruby and Data Structure Stuff (for user)



653
654
655
# File 'lib/chef/resource.rb', line 653

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

#to_textObject



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/chef/resource.rb', line 657

def to_text
  return "suppressed sensitive resource output" if sensitive

  text = "# Declared in #{@source_line}\n\n"
  text << "#{resource_name}(\"#{name}\") do\n"

  all_props = {}

  self.class.sensitive_properties.map do |p|
    all_props[p.name.to_s] = p.sensitive? ? '"*sensitive value suppressed*"' : value_to_text(p.get(self))
  rescue Chef::Exceptions::ValidationFailed
    # This space left intentionally blank, the property was probably required or had an invalid default.

  end

  ivars = instance_variables.map(&:to_sym) - HIDDEN_IVARS
  ivars.each do |ivar|
    iv = ivar.to_s.sub(/^@/, "")
    if all_props.key?(iv)
      text << "  #{iv} #{all_props[iv]}\n"
    elsif (value = instance_variable_get(ivar)) && !(value.respond_to?(:empty?) && value.empty?)
      text << "  #{iv} #{value_to_text(value)}\n"
    end
  end

  [@not_if, @only_if].flatten.each do |conditional|
    text << "  #{conditional.to_text}\n"
  end
  text << "end\n"
end

#umaskBoolean

Set a umask to be used for the duration of converging the resource. Defaults to nil, which means to use the system umask.

Parameters:

  • arg (String)

    The umask to apply while converging the resource.

Returns:

  • (Boolean)

    The umask to apply while converging the resource.



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

property :umask, [String, Integer],
desired_state: false,
introduced: "16.2",
description: "Set a umask to be used for the duration of converging the resource. Defaults to `nil`, which means to use the system umask. Unsupported on Windows because Windows lacks a direct equivalent to UNIX's umask."

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

Returns:

  • (Boolean)

    Whether the resource was updated during an action.



915
916
917
# File 'lib/chef/resource.rb', line 915

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.

Parameters:

  • true_or_false (Boolean)

    Whether the resource was updated during the current / most recent action.

Returns:

  • (Boolean)

    Whether the resource was updated during the most recent action.



927
928
929
930
# File 'lib/chef/resource.rb', line 927

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.

Returns:

  • (Boolean)

    Whether the resource was updated during the most recent action.



938
939
940
# File 'lib/chef/resource.rb', line 938

def updated_by_last_action?
  @updated_by_last_action
end

#validate_action(action) ⇒ Object

Raises:

  • (ArgumentError)


1548
1549
1550
# File 'lib/chef/resource.rb', line 1548

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



1396
1397
1398
# File 'lib/chef/resource.rb', line 1396

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

#value_to_text(value) ⇒ Object



688
689
690
# File 'lib/chef/resource.rb', line 688

def value_to_text(value)
  value.respond_to?(:to_text) ? value.to_text : value.inspect
end

#with_umaskObject



627
628
629
630
631
632
# File 'lib/chef/resource.rb', line 627

def with_umask
  old_value = ::File.umask(umask.oct) if umask
  yield
ensure
  ::File.umask(old_value) if umask
end