Chef - Lightweight Resource Provider


Advertisements

Lightweight resource provider (LWRP) provides an option of extending the list of available resources by extending it features and allows Chef user to create custom resources.

By creating custom resources one can simply write cookbooks because one can own enriched custom resources using Chef DSL which helps in making the recipe code more expressive.

In Chef community, many of the custom resources are implemented using LWRPs. There are many working examples of LWRP such as iptables_rules and apt_repository.

Working Method

Make sure one has cookbook name Testing_resource and a run_list of node which contains Testing_resource cookbook.

Building LWRP

Step 1 − Create a custom resource in Testing_resource cookbook.

vipin@laptop:~/chef-repo $ subl cookbooks/Testing_resource/resources/default.rb 
actions :create, :remove 
attribute :title, kind_of: String, default: "World" 
attribute :path, kind_of: String, default: "/tmp/greeting.txt" 

Step 2 − Create a provider for resources in Tesing_resource cookbook.

vipin@laptop:~/chef-repo $ subl cookbooks/Testing_resource/provider/default.rb 
action :create do 
   log "Adding '#{new_resource.name}' greeting as #{new_resource. 
      path}" 
   file new_resource.path do 
      content "#{new_resource.name}, #{new_resource.title}!" 
      action :create 
end  
action :remove do 
   Chef::Log.info "Removing '#{new_resource.name}' greeting #{new_resource.path}" 
   file new_resource.path do 
      action :delete 
   end 
end 

Step 3 − Use a new resource by editing Testing_resource default recipe.

vipin@laptop:~/chef-repo $ subl cookbooks/Tesing_resource/recipes/default.rb 
greeting "Ohai" do 
   title "Chef" 
   action :create 
end 

Step 4 − Upload the modified cookbook to Chef server.

vipin@laptop:~/chef-repo $ knife cookbook upload greeting 
Uploading greeting [0.1.0] 

Step 5 − Run Chef-Client on the node.

vipin@server:~$ sudo chef-client 
...TRUNCATED OUTPUT... 
2013-06-28T21:32:54+00:00] INFO: Processing greeting[Ohai] action 
create (greeting::default line 9) 
[2013-06-28T21:32:54+00:00] INFO: Adding 'Ohai' greeting as /tmp/ 
greeting.txt 
[2013-06-28T21:32:54+00:00] INFO: Processing file[/tmp/greeting. 
txt] action create (/srv/chef/file_store/cookbooks/greeting/ 
providers/default.rb line 7) 
[2013-06-28T21:32:54+00:00] INFO: entered create 
[2013-06-28T21:32:54+00:00] INFO: file[/tmp/greeting.txt] created 
file /tmp/greeting.txt 
...TRUNCATED OUTPUT... 

Step 6 − Validate the content of the generated file.

user@server:~$ cat /tmp/greeting.txt 
Ohai, Chef! 

Workflow Scripts

LWRPs live in cookbooks. A custom resource lives inside the cookbooks, and will be available under the cookbook name. In the workflow, first we define the definitions and then pass the attributes to the resources which is going to be used in the cookbook. Finally, we use those actions and attributes in our recipe.

Advertisements