4
votes

What is the difference between recipe and resource?

How to call a resource into a recipe? I can see how to include a recipe but don't understand how recipe uses resources.

2

2 Answers

3
votes

Ivan is 100% correct about recipes being a collection of resources (and arbitrary ruby code), so here's a bit more on how resources work and how to use them.

USING A RESOURCE

  1. Reference the containing cookbook in the metadata.rb

depends 'hostsfile', '2.4.5'

This will make all resources in that cookbook available within your recipes

  1. Call the resource by its name-spaced name.

This is created by chef from the cookbook name and the resource's name. There are a few rules it follows with the naming convention that can confuse you if you do not follow the best practice of snake-case.

  • Both resource and cookbook will be in all lowercase
  • All hyphens will become underscores ( '-' >>> '_' )
  • The default name is cookbook_resource

so a cookbook COOLEST-COOKBOOK with the resource rAd_ReSoUrCe would become coolest_cookbook_rad_resource 'resource name'

RESOURCE TYPES

There are three commonly used resource types. In order from least used to most used they are:

  1. Heavyweight Resource Provider (HWRP)
  2. Lightweight Resource Provider (LWRP)
  3. Custom Resource

HWRP's allow for a great deal of control over name-spacing but require a great deal of work, comparatively.

LWRP's are a great replacement for HWRP's but still have boiler plate code associated with them. They also require you to maintain two separate files, a provider and a resource. The resource declares the attributes associated with the LWRP and the Provider provides the logic for what the resource does when it is called.

Custom Resources allow you to maintain a single file that has both the properties(analogues to attributes) and logic. It also eliminates pretty much all the boiler plate code associated with LWRP's. You will have to be on chef-client 12.4+ to make use of Custom Resources.

UNDERSTANDING A RESOURCE

The only way to really understand what a resource does it to look at its source code, as the I/O of resources really are a black box. A great resource for understanding what custom resources can do is https://docs.chef.io/custom_resources.html, and you can find HWRP and LWRP explanations via search engines pretty readily.

2
votes

Chef recipe is just a sequence of resources (plus sometimes other stuff like variable definitions) which have their actions executed in order of definition.

Is mostly a collection of resources, defined using patterns (resource names, attribute-value pairs, and actions) (c) docs

Here's an example resource creating a file with specified contents. Chef resources doc has examples of what is possible to be done with those.

file '/var/www/public_html/index.php' do
  content '<html>This is a placeholder for the home page.</html>'
  mode '0755'
  owner 'admin'
  group 'admin'
  action :create
end