How do I execute ruby code in libraries/default.rb during converge time?


#1

I have use a cookbook that uses the package, execute, and template resource like so

package 'some_package'

# some_package RPM installs /opt/somefile.conf
execute 'Copy somefile.conf to /tmp'
  command 'cp /opt/somefile.conf /tmp'
end

template '/etc/somefile.conf' do
  source 'somefile.conf.erb'
  variables {{
     :some_var => some_library_function
  })
end

Then i have libraries/default.rb like so

def some_library_function
  conf_file = '/tmp/somefile.conf'
  File.foreach(conf_file) do |line|
    # Do something with line to get some_var for template
  end
end

However libraries/default.rb function is evaluated during compile time, and fails during compile time since /tmp/somefile.conf in not there yet.

How do I make the above library function run at converge time?

NOTE: This is a simplified example. I DO want/need to keep the function in the libraries/default.rb file


#2

As with any other resource property, you can use lazy{}:

template '/etc/somefile.conf' do
  source 'somefile.conf.erb'
  variables lazy {
     {:some_var => some_library_function}
  }
end

#3

coderanger, you da man! Thanks for reminding me of that trick, which worked in my case!