Search code examples
chef-infrachef-recipe

In Chef, how do you notify a resource outside of a resource?


I want to create an execute resource which sets up some environment variables and calls a certain command. But this execute resource should just be a sort of "method", i.e. define some functionality that I can reuse later. I want to be able to trigger this execute from other recipes, and currently I am using a ruby_block although I have a feeling I am doing something wrong. (My cookbook is called commands)

This is my reusable functionality:

# default.rb

execute 'Run command' do
  Chef::Log.info("Running command: #{node['task']}")

  command node['task']
  cwd deploy[:current_path]
  environment (node[:task] || {})
  action :nothing
  not_if node[:task].nil?
end

And this is one of the specific tasks which utilises it:

# rake_db_migrate.rb

include_recipe 'commands'

node.set[:task] = 'rake db:migrate'

ruby_block 'Trigger command' do
  block {}
  notifies :run, 'execute[Run command]', :immediately    
end

I also want to be able to run this with arbitrary tasks by setting a property on the node, which is essentially the same as the above but without writing to node['task']:

# run.rb

include_recipe 'commands'

ruby_block 'Trigger command' do
  block {}
  notifies :run, 'execute[Run command]', :immediately    
end

Essentially I want to define some reusable functionality in default.rb, and then be able to use this from other recipes, like run.rb and rake_db_migrate.rb, is this the right way or am I missing something?


Solution

  • In this case you probably want to use a definition: http://docs.chef.io/definitions.html

    define the reusable bits and use 'task' as a parameter.