Writing chef Library

In many cases we have to reuse same code again and again in our recipes. So to reduce this we can write our own library module and reuse it’s methods whenever required. This can help us use our own custom methods.

Like in my previous post we have to access the environment variables in many recipes. So we can use the same code as our library to create a module (lets say ProdEnvSetup)

 

  1. Create a library file under library directory of cook-book.(cook-book/library/envsetup.rb) and add below code.

 

module ProdEnvSetup
def setupenv()
hash1 = {}
File.open("/u01/data/wor/app/conf/conf.prop") do |fp|
fp.each do |line|
key, value = line.chomp.split("=",2)
hash1[key] = value
end
end

hash1.each do |key,value|
skey = "#{key.to_s}".gsub(/\s|"|'/, '')
svalue = "#{value.to_s}".gsub(/\s|"|'/, '')
ENV[skey] = svalue
end
end
end
end

2. Using library inside recipe ( 1st way )

So if the same environment variables are required inside a recipe, we can directly include the module inside our recipe.

Use below code inside begining of recipe:

class Chef::Recipe
include ProdEnvSetup
end
setupenv() 

2. Using library ( 2nd way )

We can add additional encapsulation to our module by keeping it inside a recipe and include that recipe in every recipe, wherever its required.

create a recipe setupenv.rb and add above codes in 1st way(above)

and include it in other recipes like this:

include "prod-multiode-cookbook:setupenv"

 


					
Advertisements

About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps in in Public/Private cloud domain. my @github : https://github.com/kumarprd my @nagiosexchange : https://exchange.nagios.org/directory/Owner/divyaimca/1 my @linkedin : https://www.linkedin.com/in/priyadarshee-kumar-☁-a9415615
This entry was posted in ARTICLES, DevOps, HOWTO, Programming, SCRIPTING, TIPS & T RICS, TUTORIALS and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s