anonymous
anonymous

Reputation: 1968

Use library cookbook inside resources

I am trying to learn library cookbook and wrote one test library cookbook named nol. Inside nol/libraries/nol_helper.rb I have below code

module Nol
  module Helper

    include Chef::Mixin::ShellOut

    def has_bacon?
      cmd = shell_out!('getent passwd bacon', {:returns => [0,2]})
      cmd.stderr.empty? && (cmd.stdout =~ /^bacon/)
    end
  end
end

In second cookbook I am trying to include it in default.rb recipe as

class Chef::Resource::User
        include Nol::Helper
end

user 'noi' do
    action :create
    only_if { has_balcon? }
end

But chef keeps on giving below error

 ================================================================================
    Error executing action `create` on resource 'user[noi]'
    ================================================================================

    NoMethodError
    -------------
    undefined method `has_balcon?' for Chef::Resource::User

Thanks

Upvotes: 0

Views: 638

Answers (2)

Oleksandr Slynko
Oleksandr Slynko

Reputation: 787

If you really want to add this method to user resource, you should extend provider ::Chef::Provider::User.send(:include, Nol::Helper)

Upvotes: 1

coderanger
coderanger

Reputation: 54249

So two things, one you have a simple typo in there, but more importantly it is really not recommended to monkeypatch core Chef classes.

You can accomplish something similar without patching by using a module method instead:

module Nol
  def self.has_bacon
    # As before ....
  end
end

user 'noi' do
  only_if { Nol.has_bacon? }
end

Upvotes: 4

Related Questions