Search code examples
rubycookbookchef-infra

Creating dynamic resource in cookbook


Long story short, here is my code:

template "...." do

    ....

    notifies :restart,"service[myservice_One]"
    notifies :restart,"service[myservice_Two]"
end

['One', 'Two'].each do |proj|
    service 'myservice_#{proj}' do 
        start_command "setsid /etc/init.d/my_command #{proj} start"
        stop_command "setsid /etc/init.d/my_command #{proj} stop"
        restart_command "setsid /etc/init.d/my_command #{proj} restart"
        status_command "setsid /etc/init.d/my_command #{proj} status"
        supports :status => true, :restart => true
        action [:enable,:start]
    end
end

I got this error:

template[...] is configured to notify resource service[celery_worker_One] with action restart, but service[celery_worker_One] cannot be found in the resource collection.

I know I can duplicate my code to make it work but how to dynamically create the services?

Thanks!


Solution

  • In Ruby,

    'myservice_#{proj}'
    

    and

    "myservice_#{proj}"
    

    are very different:

    'myservice_#{proj}' #=> "myservice_#{proj}"
    "myservice_#{proj}" #=> "myservice_One"
    

    If you need interpolation, you must use double quotes. This is why you cannot notify your resource.