Question

Let's say I have :

ruby_block "foo" do
  block do
     puts "do something"
  end
end

ruby_block "bar" do
  block do
    puts "do something else"
  end
end

How can I call bar from foo block?

Was it helpful?

Solution

If you have generic functionality you want to implement in Ruby, you should instead write library functions and call them from your ruby_blocks.

You can e.g add this into libraries/helpers.rb:

module MyCookbook
  module Helpers
    def foo
      # do something
    end

    def bar
      # do something else
    end
  end
end

Then you can call these functions in your ruby_blocks like this:

extend MyCookbook::Helpers

ruby_block "foo" do
  block do
    foo
  end
end

ruby_block "bar" do
  block do
    # call the foo helper method
    foo
    # call the bar helper method
    bar
  end
end

In addition to the helper methods, you can also use notifications which are available in Chef's DSL to notify other resources to run, including other ruby_blocks.

OTHER TIPS

Holger's answer is the "right thing to do", but if you need to call one resource from inside another, you can leverage the return value of the DSL methods.

Each Recipe DSL method (file, ruby_block, etc) returns the instance of the object created from the DSL:

bar = ruby_block 'bar' do
  # ...
end

Now bar contains a reference to the Chef::Resource::RubyBlock instance that was created by the DSL method. You can then leverage this in the other ruby_block:

ruby_block 'foo' do
  block do
    # in this context, bar is the RubyBlock resource, so you can call any actions
    # or change any attributes you wish.
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top