2

I have a cookbook my_service with a custom resource write_config. This resource is called from another cookbook node_a.

  • my_service/resources/write_config.rb:

    property :template_source, String, name_property: true 
    property :calling_cookbook, String, required: true
    
    action :create do
      template "/tmp/test.txt" do
        source   template_source
        cookbook calling_cookbook
        owner    'root'
        mode     '0644'
        action   :create
      end
    end
    
  • Node cookbook recipe node_a/default.rb:

    my_service_write_config 'config.erb' do
      calling_cookbook 'node_a'
    end
    

This works fine, but I would like to get rid of the calling_cookbook property.

Is there a way to automatically get the calling_cookbook name?

Solution

(Thank you coderanger!) The basic resource template seems to get evaluated in the context of the calling (node_a) cookbook (?).

  • my_service/resources/write_config.rb:

    property :template_source, String, name_property: true 
    action :create do
      template "/tmp/test.txt" do
        source   template_source
        owner    'root'
        mode     '0644'
        action   :create
      end
    end
    
  • Using it within the node cookbook recipe node_a/default.rb becomes a one-liner:

    ...
    include_recipe 'my_service'
    my_service_write_config 'config.erb'
    ...
    

Neat!

Community
  • 1
  • 1
andiba
  • 1,508
  • 2
  • 11
  • 22
  • I believe this is not possible, since during the chef-client run the node has a mashup of all attributes, recipes and cookbooks that will use. There is an attribute node['cookbooks'] with all the cookbooks that the node will use during the run, but this is quite useless for this scenario. If you are experimenting with custom resources, maybe using templates like this is not the best approach, try sharing the scope of this custom resource and maybe we could find a better solution. – Navarro Apr 20 '17 at 15:35

1 Answers1

2

This is tracked automatically as new_resource.cookbook_name. You may need to to_s it because somehow it ends up a symbol sometimes but otherwise should be what you need.

Also specifically for templates this is already the default behavior if you just remove the cookbook line.

coderanger
  • 52,400
  • 4
  • 52
  • 75