Chef Tutorial
Advanced Chef
Chef Useful Resources
Selected Reading
- Chef - Chef-Client Run
- Chef - Nodes
- Testing Cookbook with Test Kitchen
- Chef - ChefSpec
- Chef - Foodcritic
- Chef - Testing Cookbooks
- Chef - Chef-Shell
- Chef - Chef-Client as Daemon
- Chef - Environment
- Chef - Roles
- Chef - Cookbook Dependencies
- Chef - Cookbooks
- Chef - Solo Setup
- Chef - Knife Setup
- Chef - Test Kitchen Setup
- Chef - Client Setup
- Chef - Workstation Setup
- Chef - Version Control System Setup
- Chef - Architecture
- Chef - Overview
- Chef - Home
Advanced Chef
- Chef - Community Cookbooks
- Chef - Files & Packages
- Chef - Blueprints
- Lightweight Resource Provider
- Chef - Resources
- Chef - Cross-Platform Cookbooks
- Chef - Scripts for Data Bags
- Chef - Data Bags
- Chef - Environment Variable
- Chef - Definition
- Chef - Libraries
- Chef - Ruby Gems with Recipes
- Chef - Plain Ruby with Chef DSL
- Chef - Templates
- Dynamically Configuring Recipes
Chef Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Chef - Libraries
Chef - Libraries
Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.
Creating the Library
Step 1 − Create a helper method in cookbook’s pbrary.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/pbraries/ipaddress.rb class Chef::Recipe def netmask(ipaddress) IPAddress(ipaddress).netmask end end
Step 2 − Use the helper method.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb ip = 10.10.0.0/24 mask = netmask(ip) # here we use the pbrary method Chef::Log.info("Netmask of #{ip}: #{mask}")
Step 3 − Upload the modified cookbook to the Chef Server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook Uploading my_cookbook [0.1.0]
Testing the Library
user@server $ sudo chef-cpent ...TRUNCATED OUTPUT... [2013-01-18T14:38:26+00:00] INFO: Netmask of 10.10.0.0/24: 255.255.255.0 ...TRUNCATED OUTPUT...
Working Method
Chef pbrary code can open the chef::Recipe class and add new methods as done in Step 1. This step is not the cleanest but the simplest way of doing it.
class Chef::Recipe def netmask(ipaddress) ... end end
Best Practices
Once we open the chef::recipe class, there are changes that it gets polluted. As a best practice, it is always a better way to introduce a new sub class inside the pbrary and define a method as class method. This avoids pulpng the chef::recipe namespace.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/pbraries/ipaddress.rb class Chef::Recipe::IPAddress def self.netmask(ipaddress) IPAddress(ipaddress).netmask end end
We can use the method inside the recipe pke
IPAddress.netmask(ip)Advertisements