Chef/ruby way – Read a file and expose as environment variable

Many time we have to read a property file in in which the variable and value are comma separated and we have to set those in our environment variable to execute certain recipes.

 

e.g. property file (/u01/data/wor/app/conf/conf.prop)

ops_home = ‘/u01/data/work/app/ops-home-1.2.30’

node_instance = ‘/u01/data/work/app’

 

So here we have to read the file , create a hash and then save the LHS as key and RHS as value. Then we are good to expose them as environment variable.

Note : This is the approach I used, there may be other solution available.

Here the properties are = separated. It can be any separator.

This is a reusable function and can be called where ever required.

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</pre>
hash1.each do |key,value|
skey = "#{key.to_s}".gsub(/\s|"|'/, '')
svalue = "#{value.to_s}".gsub(/\s|"|'/, '')
ENV[skey] = svalue
end
end
end
end

 

Here setupenv( ) can be called anywhere the ENV variables are required.

Note : Here gsub(/\s|”|’/, ”) is used to trim  leading and trailing space, single quote, double quote of the key and value.

 

 

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, TUTORIALS, Uncategorized 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