StephenKing
StephenKing

Reputation: 37600

Chef: Use library function in attributes

How can I access an own library function (created in the following module) in a cookbook's attribute file?

module Gerrit
  module Helpers
    def gerrit_above?(version)
      require 'chef/version_constraint'
      Chef::VersionConstraint.new(">= #{version}").include?(node['gerrit']['version'])
    end
  end
end

Chef::Recipe.send(:include, ::Gerrit::Helpers)
Chef::Resource.send(:include, ::Gerrit::Helpers)
Chef::Provider.send(:include, ::Gerrit::Helpers)

I can access it in recipes through gerrit_above?, but didn't find a way to make it at the same time usable in an attributes file. I tried the following line

Chef::Node::Attribute.send(:include, ::Gerrit::Helpers)

But then it fails while accessing node with:

Undefined method or attribute `node' on `node'

Has anyone a clean solution?

Upvotes: 4

Views: 3110

Answers (1)

Jeff
Jeff

Reputation: 520

I would recommend using the node.run_state object to store transient data between resources and recipes. See more info here: https://docs.chef.io/recipes/#noderun_state

If you absolutely have to store data within attributes, create a recipe which computes and sets the attribute values and set this as the first recipe that gets executed in the default recipe.

Upvotes: 1

Related Questions