MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Chef Tutorials: Common Resource Functionality in chef Cookbook recipe

Common resource properties are settings that every Chef Infra resource accepts, whatever the resource type: action, ignore_failure, retries, retry_delay, sensitive, guards such as not_if and only_if, and notifications. This page explains how the ignore_failure, retries and retry_delay examples above behave at run time. It then covers the other common properties and shows how to test them in a recipe.


Chef docs on common resource properties: compile_time, ignore_failure, retries, retry_delay, sensitive

Examples 

The following examples show how to use common properties in a recipe.

Use the ignore_failure common property


gem_package 'syntax' do
  action :install
  ignore_failure true
end
Use the retries and retry_delay common properties


service 'apache' do
  action [ :enable, :start ]
  retries 3
  retry_delay 5
endCode language: JavaScript (javascript)

What common resource properties are

Each Chef resource has its own properties. For example, package has version and template has source. Chef also defines a set of properties on the base resource class, and every resource inherits them. Because of that, you can add retries 3 to a package, execute, service or remote_file resource and it works the same way on each one.

PropertyType and defaultWhat it does
actionSymbol or array; default depends on the resourceThe action or actions to run, for example :install or [:enable, :start]
ignore_failuretrue, false or :quiet; default falseLets the Chef run continue if this resource fails. :quiet also suppresses the error output
retriesInteger; default 0How many more times to try the resource after it raises an error
retry_delayInteger (seconds); default 2How long to wait between retries
sensitivetrue or false; default falseHides property values and diffs from logs and output
not_if / only_ifBlock or command stringGuards that decide whether the resource runs
notifies / subscribesAction, resource, timerTrigger an action on another resource when this one changes
compile_timetrue or false; default falseRuns the resource during the compile phase instead of the converge phase

How the example above behaves

In the first example, ignore_failure true on the gem_package resource means that if the syntax gem fails to install (for example, because there is no network access to the gem source), Chef logs the error and moves on to the next resource. The run still finishes successfully. Use this only when the resource really is optional. It hides real problems, and a resource that fails does not fire its notifications.

In the second example, retries 3 and retry_delay 5 make Chef retry the service resource up to three more times, waiting 5 seconds between attempts. That gives up to four attempts in total. If the last attempt also fails, the run fails, unless ignore_failure is also set. Retries help with problems that clear up on their own, such as a package mirror that is briefly down, a service that depends on something still starting, or a slow download.

Note: Retries do not fix configuration errors. If a service fails because its configuration file is invalid, retries only add delay before the same failure. Keep retries for operations that can fail temporarily.

Corrected and complete version of the example

Most Linux distributions do not have a service called apache. Debian and Ubuntu call it apache2, and RHEL-family systems call it httpd. The recipe below picks the right names for the platform, installs the package first, and puts both common-property examples into a recipe you can run.

# recipes/default.rb

apache_pkg = platform_family?('debian') ? 'apache2' : 'httpd'

# Optional gem: do not fail the whole run if it cannot be installed
gem_package 'syntax' do
  action :install
  ignore_failure true
end

# Package installs can fail briefly when a mirror is unavailable
package apache_pkg do
  action :install
  retries 3
  retry_delay 10
end

service apache_pkg do
  action [:enable, :start]
  retries 3
  retry_delay 5
endCode language: PHP (php)

platform_family? is a built-in recipe helper. debian covers Debian and Ubuntu, and other families such as rhel, fedora and amazon fall back to httpd. You can extend the condition if you support other platforms.

Guards: not_if and only_if

Guards make a resource run only when it needs to. Most built-in resources are already idempotent, but execute, bash and script resources are not, so they usually need a guard. A guard can be a Ruby block, which is evaluated inside the Chef process, or a string, which runs as a shell command where an exit code of 0 means true.

execute 'initialise-app-db' do
  command '/opt/app/bin/init-db'
  # Ruby block guard: skip if the marker file already exists
  not_if { ::File.exist?('/opt/app/.db_initialised') }
end

execute 'reload-sysctl' do
  command 'sysctl --system'
  # String guard: run only if the setting is present in the config file
  only_if 'grep -q net.ipv4.ip_forward /etc/sysctl.conf'
endCode language: PHP (php)

Ruby block guards are faster and portable because they do not start a shell. String guards accept options such as user, group, cwd, environment and timeout, for example not_if 'test -f done', cwd: '/opt/app'. On Windows, the guard_interpreter property controls which interpreter runs string guards.

Notifications: notifies and subscribes

Notifications connect resources. When a resource actually changes something, it can trigger an action on another resource. The usual case is restarting a service after its configuration file changes.

template '/etc/apache2/sites-available/app.conf' do
  source 'app.conf.erb'
  notifies :reload, 'service[apache2]', :delayed
end

service 'apache2' do
  action [:enable, :start]
  # Equivalent reverse form:
  # subscribes :reload, 'template[/etc/apache2/sites-available/app.conf]', :delayed
endCode language: PHP (php)
  • :delayed (the default) queues the action until the end of the run, and runs it only once even if many resources send the same notification.
  • :immediately (or :immediate) runs the action straight after the notifying resource.
  • :before runs the action before the notifying resource, and only if that resource is about to make a change.
  • Notifications fire only when the resource is updated. If the template content has not changed, the service is not reloaded.
  • A resource used only as a notification target usually has action :nothing, so it runs only when notified.

sensitive and compile_time

Set sensitive true on any resource that handles secrets. Chef then stops printing property values, command lines and file diffs to the console and logs, and keeps them out of reporting data.

template '/etc/app/db.yml' do
  source 'db.yml.erb'
  variables(password: data_bag_item('secrets', 'db')['password'])
  mode '0600'
  sensitive true
end

# Install a gem during the compile phase so later recipe code can require it
chef_gem 'aws-sdk-s3' do
  compile_time true
endCode language: PHP (php)

Chef runs in two phases. In the compile phase it reads all recipes and builds a resource collection, and in the converge phase it runs those resources in order. compile_time true runs the resource while the recipe is being compiled. Use it only when later Ruby code in the recipe needs the result immediately, for example a gem it will require. An older pattern that does the same thing is resource.run_action(:action).

Running and testing the recipe

You do not need a Chef Infra Server to try these properties. Use chef-apply for a single recipe file, or local mode for a whole cookbook. Both need administrator rights because they change the system.

# Single recipe file
sudo chef-apply common_props.rb

# Whole cookbook in local mode (run from the chef-repo directory)
sudo chef-client --local-mode --runlist 'recipe[mycookbook::default]'

# Lint the cookbook before running it
cookstyle cookbooks/mycookbookCode language: PHP (php)

In the output, look for the resources being marked as updated or up to date. Run it a second time to check idempotency: guarded execute resources should be skipped, and no notifications should fire if nothing changed. To see retries happen, point a remote_file resource at a URL that does not exist and set retries 2. You will see the retry messages and the delay between attempts.

Common mistakes and best practices

  • Using ignore_failure to hide bugs. Fix the cause instead. If a step really is optional, add a comment explaining why.
  • Expecting retries to mean total attempts. retries 3 means one attempt plus three retries.
  • Leaving out sensitive true on secrets. Passwords in execute commands and templates appear in logs and CI output by default.
  • Using a string guard where a Ruby block would do. Each string guard starts a shell. ::File.exist? is faster and works on every platform.
  • Wrong resource name in a notification. 'service[apache]' must match an existing resource name exactly. If it does not, the run fails with an error saying the resource cannot be found.
  • Overusing compile_time. Running resources at compile time breaks the normal ordering and makes recipes harder to follow.

Frequently asked questions

Does retries 3 in Chef mean three attempts or four?

Four. Chef makes the first attempt and then retries up to three more times if it raises an error, waiting retry_delay seconds (default 2) between attempts.

What is the difference between ignore_failure true and ignore_failure :quiet?

Both let the Chef run continue after the resource fails. With true, the error is still printed. With :quiet, the error output is suppressed, which is useful for expected failures but makes problems harder to troubleshoot.

When should I use not_if instead of only_if?

Use not_if when the resource should be skipped if a condition is true, such as a marker file existing. Use only_if when the resource should run only if a condition is true. They are opposites, and you can use both on the same resource.

Why did my notification not trigger a service restart?

Notifications fire only when the notifying resource is updated. If the file or template content did not change, nothing is sent. Also check that the target name, such as service[apache2], matches the resource name exactly.

Do common properties work with custom resources?

Yes. Custom resources inherit from the base Chef resource class, so retries, ignore_failure, guards, notifications and sensitive all work on them the same way as on built-in resources.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Chef Tutorials: How to looping and iterative in Chef Cookbook recipe?

Chef recipes are Ruby, so you loop with ordinary Ruby iterators such as each, and each pass declares one Chef resource. This page explains how the loop…

Read More

Chef Tutorials: How to set Conditions in Chef Cookbooks recipe using Guard?

Chef guards are the not_if and only_if properties, which decide during the converge phase whether a resource runs. A guard can be a shell command string or…

Read More

Chef Tutorials: template Resource with example

The Chef template resource renders an Embedded Ruby (ERB) file from a cookbook's templates/ directory and writes the result to a path on the node. This page…

Read More

Chef Training Roadmap for DevOps Engineers: Course Tracks, Lab Workflow, and Practical Commands

This guide turns a promotional Chef training post into a practical roadmap for engineers. Compare course levels, understand the learning workflow, and use hands-on commands you can run in a lab.

Read More

Provision an AWS EC2 Instance with Chef (Legacy ChefDK Workflow)

A practical, step-by-step walkthrough for provisioning an AWS EC2 VM using the classic ChefDK and chef-provisioning approach. Includes workflow, commands, recipe examples, and validation checks for legacy environments.

Read More

Chef Command-Line Reference: Essential chef-solo, chef-client, and Knife Workflows

A task-oriented reference for frequently used Chef and Knife commands, from cookbook scaffolding to node bootstrap and run-list management. Includes workflow guidance and copy-ready command examples.

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x