wait until the end of Chefs compile phase before running code block?

309 views Asked by At

I want to check the contents of the resource_collection within a recipe to see if a specific LWRP is being called during the nodes run. But due to the compile load logic and cookbook name ordering etc.. it's difficult to do something like this:

if run_context.resource_collection.any?{|r| r.resource_name.to_s == 'my_lwrp_resource'}

    template "/tmp/example.rb" do
      source      "test.erb"
      action      :nothing
    end.run_action(:create)

end

because this code might be run before all resources have been added to the resource_collection.

Is there any way to defer running this code until the end of the compile phase to ensure the resource_collection is fully populated and the query will correctly find the resource ?

thanks

1

There are 1 answers

0
Martin On

You can define a ruby_block resource that will be executed during converge. You won't have access to the recipe DSL there, to define the template resource using the DSL, but defining a template resource in ruby is just as easy:

ruby_block 'run_my_template_resource' do
  action :create
  block do
    r = Chef::Resource::Template.new('template_name', run_context)
    r.path       '/path/to/write.to'
    r.source     'source.erb'
    r.cookbook   'cookbook-name'
    r.owner      'root'
    r.group      'root'
    r.mode       00600
    r.variables  my: 'variables'
    r.run_action :create
  end
end