'Refer to subresource in two actions of custom resource

Suppose I have a custom resource that has it's main action as something like:

action :create do
  # some other stuff
  service "my-service" do
    action :start
  end
end

But I want resources external to the custom resource to be able to notify it to restart the service inside it.

notifies :restart, 'service[my-service]', :delayed doesn't work, because it can't find service[my-service].

Is having a seperate action like:

action :restart
  service 'my-service' do
    action :restart
  end
end

the correct way to do this?

Is there a better way to refer to the same resource besides re-defining it in the restart action?



Solution 1:[1]

You could try something similar to this approach:

actionable = :create if something
actionable = :restart if something_else

and then modify your resources like this:

  service "my-service" do
    action actionable
  end

Solution 2:[2]

You can only notify up so if you need it to be visible to recipe code and other subresources you have to create it in the root run context:

action :create do
  with_run_context :root do
    edit_resource(:service, 'my-service') do |new_resource|
      action :nothing
      delayed_action :restart
    end
  end
end

That should create a service resource in the root run context and send a delayed restart to it. The new_resource argument isn't necessary but it is a good habit to get into when using edit_resource.

Solution 3:[3]

Another option is to reverse the notification system and use subscribes to restart my-service. That way, we wouldn't need to handle it in the custom resource.

For example:

# shown for completeness of example
file '/tmp/testfile' do
  content 'foo'
end

service 'my-service.service' do
  action :nothing
  subscribes :restart, 'file[/tmp/testfile]', :delayed
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MCorrea
Solution 2 lamont
Solution 3