Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Cookbooks and Attributes

Writing Custom Resources in Chef

Write your own Chef resources: files in resources/, property and action blocks, default actions, converge_if_changed, load_current_value, and a Ruby model of the pattern.

The built-in resources cover a lot, but every team has things of its own: a web site configured on nginx, an application deployed to a certain layout, a database user with certain grants. A custom resource lets you package that logic once and use it like any built-in resource, with properties, actions and idempotence. It replaces the old definitions and LWRPs, and it is the right way to share code between recipes. Real syntax is read-only here, and a Ruby stand-in models the pattern so you can run it.

Your first custom resource

A custom resource is one file in the cookbook's resources/ folder. The file name (plus the cookbook name) becomes the resource name: webserver/resources/site.rb defines webserver_site.

Ruby
# resources/site.rb
provides :webserver_site
unified_mode true

property :domain, String, name_property: true
property :port, Integer, default: 80
property :root, String, default: lazy { "/var/www/#{domain}" }

action :create do
  directory new_resource.root do
    recursive true
  end

  file "#{new_resource.root}/index.html" do
    content "<h1>#{new_resource.domain}</h1>"
  end

  template "/etc/nginx/conf.d/#{new_resource.domain}.conf" do
    source 'site.conf.erb'
    cookbook 'webserver'
    variables(domain: new_resource.domain, port: new_resource.port, root: new_resource.root)
    notifies :reload, 'service[nginx]', :delayed
  end
end

action :delete do
  file "/etc/nginx/conf.d/#{new_resource.domain}.conf" do
    action :delete
  end
end

Use it in a recipe like any resource:

Ruby
webserver_site 'blog.example.com' do
  port 8080
end

webserver_site 'old.example.com' do
  action :delete
end

The pieces:

  • property: declares an input with a name, a type, and options (default, name_property, required: true, equal_to: [...]). name_property: true fills the property from the string after the resource type.
  • action: a block of Chef code, using other resources, that brings the system to the desired state. The first action is the default.
  • new_resource: inside an action, the object that holds the values the user gave.
  • unified_mode true: evaluates the action's resources while the custom resource runs, instead of in a separate collection (the modern default behavior; recommended for new resources).

Because an action is built from other resources, a custom resource is automatically idempotent whenever those inner resources are.

Property rules and validation

Ruby
property :port, Integer, default: 80, callbacks: {
  'must be between 1 and 65535' => ->(p) { p.between?(1, 65535) }
}
property :ensure_mode, String, equal_to: %w(strict relaxed), default: 'strict'
property :packages, Array, default: lazy { %w(nginx) }

Types (String, Integer, Array, Hash, [true, false]) are checked, and errors are raised before the action runs. Use lazy { } for defaults that depend on other properties, as root does above.

converge_if_changed and load_current_value

For resources that manage a single thing with state, Chef offers a pattern that handles the "compare then act" logic for you:

Ruby
property :setting, String, name_property: true
property :value, String

load_current_value do |new_resource|
  current_value_does_not_exist! unless ::File.exist?("/etc/app/#{new_resource.setting}")
  value ::File.read("/etc/app/#{new_resource.setting}").strip
end

action :set do
  converge_if_changed :value do
    file "/etc/app/#{new_resource.setting}" do
      content "#{new_resource.value}\n"
    end
  end
end

load_current_value reads the real state into current_resource. converge_if_changed compares the properties you name with their current values and runs its block (and marks the resource updated) only if something differs. It also prints a nice summary of what changed.

Stand-in: a custom resource in plain Ruby

The stand-in models properties with defaults, validation and the compare-then-act flow. It is not Chef's resource DSL, but the structure matches closely.

Ruby Stand-in: a custom resource with properties and actions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The three create calls show the three outcomes: created, up to date, updated. The last shows validation stopping a bad value before any action runs. Real custom resources give you all of this with less code, because property and converge_if_changed do the work.

Libraries and helpers

Logic that several resources share can go in a helper module. In a custom resource, action_class do ... end adds methods available inside actions:

Ruby
action_class do
  def config_path
    "/etc/nginx/conf.d/#{new_resource.domain}.conf"
  end
end

Large helper classes belong in libraries/. Keep actions short and readable; each action should read like a recipe.

Testing custom resources

Test them with Test Kitchen by using the resource in a small test cookbook recipe and verifying the result with InSpec, or with ChefSpec's custom matchers. The testing chapter later in this course covers both. Until then, remember that a well-designed custom resource has few properties, sensible defaults, clear validation and actions that can be run twice without changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the file for the resource webserver_site live?

    Custom resources are files in the cookbook's resources/ folder; the name is cookbook plus file name.
  2. 2. What does name_property: true do?

    For webserver_site 'a.example.com', the string becomes the value of the name property.
  3. 3. What does converge_if_changed do?

    It compares desired and current values and converges only on a difference.
  4. 4. Why is a custom resource made of other resources usually idempotent?

    Each inner resource compares current and desired state, so the whole action is safe to repeat.

Summary

  • A custom resource is a file in resources/ with property and action blocks, named cookbook_resource.
  • Properties have types, defaults, validation and a name property; new_resource holds the user's values.
  • load_current_value plus converge_if_changed implement compare-then-act.
  • Build actions from existing resources to inherit idempotence; keep them small and test them.

Back to the track: Chef