Writing a first library


#1

Hi, everybody!

I’m trying to write my first library in Chef 11.18.0 (chef-solo) and using
this article as an example:

However, this piece of code isn’t working for me:
libraries/sensitives_helper.rb:

  1. require ‘chef/mixin/shell_out’
  2. module SensitivesHelper
  3. include Chef::Mixin::ShellOut
  4. def self.retrieve_token(type, version)
  5. Chef::Log.info "Retrieving sensitive for token #{type}, version
    

#{version}"
9. cmd = shell_out!(’/usr/local/bin/get-sensitives.sh’, type, version
)
10. Chef::Log.info "Retrieved sensitive token: #{cmd.stdout}"
11. cmd.stdout
12. end
13.
14. end
15.
16. Chef::Recipe.send(:include, SensitivesHelper)

When I try to use it in recipe, it’s causing NoMethodError: undefined
method `shell_out!’ for SensitivesHelper:Module

Usage example:

user = ''
ruby_block “get sensitives” do
block do
user = SensitivesHelper.retrieve_token(‘a’, ‘b’)
end
end

Any help is appreciated.


Andrey.


#2

On Monday, May 4, 2015 at 10:49 AM, Andrey Brindeyev wrote:

Hi, everybody!

I’m trying to write my first library in Chef 11.18.0 (chef-solo) and using this article as an example:
https://www.chef.io/blog/2014/03/12/writing-libraries-in-chef-cookbooks/

However, this piece of code isn’t working for me:
libraries/sensitives_helper.rb:
require ‘chef/mixin/shell_out’

module SensitivesHelper

include Chef::Mixin::ShellOut

def self.retrieve_token(type, version)

Chef::Log.info “Retrieving sensitive for token #{type}, version #{version}”

cmd = shell_out!(’/usr/local/bin/get-sensitives.sh (http://get-sensitives.sh)’, type, version)

Chef::Log.info “Retrieved sensitive token: #{cmd.stdout}”

cmd.stdout

end

end

Chef::Recipe.send(:include, SensitivesHelper)

When I try to use it in recipe, it’s causing NoMethodError: undefined method `shell_out!’ for SensitivesHelper:Module

Usage example:

user = ''
ruby_block “get sensitives” do
block do
user = SensitivesHelper.retrieve_token(‘a’, ‘b’)
end
end

Any help is appreciated.


Andrey.

The issue is class vs. instance methods. This blog post describes the difference: http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

When mixing in methods for use as class methods, you need to use extend instead of include: This post describes the difference between those two: http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

HTH,


Daniel DeLeo