Ruby methods useable in many recipes


#1

Hey guys,
i searched a little bit and didn't find a good solution for my problem.
My problem is that i want to use a ruby method in different recipes and I do not know how.
How do you guys handle it?


#2

You could create a ruby gem, host that in your versioning system and then import it into your cookbooks.

https://guides.rubygems.org/make-your-own-gem/


#3

So,
What you could do is create in your shared cookbook a libraries/methods.rb file and there you could write something like :

module SharedMethods
  def hello
    puts "Hello"
  end
end

And then in your recipes you can do ::SharedMethods.hello()


#4

Put it in a module as a library in one of the core , relevant cookbook. Declare that cookbook as dependency and extend the module in your consumer cookbook /recipes for reuse


#5

You could create a custom resource to reuse across your cookbook. https://docs.chef.io/custom_resources.html


#6

I've read about this method, but creating the cookbook with chef generate doesn't create the folder libraries.
In the deprecated version with knife cookbook create the folder was created.
So I do not exactly know how i could create it, so i could use it in my chef recipes.


#7

I've read about this possibility, but the thing is my method is pure ruby functionality and it has few lines of code.
But it is important and i do not want to copy and paste it to the other recipes, instead i would like to put it somewhere so i could include it in the recipes, but I don't know how exactly this could work.


#8

In recipe you only specify the custom resource. Consider it's like a function with parameters to be passed.


#9

There is nothing magical about creating the directory, chef generate and knife cookbook create are just opinionated generators that have zero bearing on actual functionality. If you create the directory manually it works just like you'd expect.