Search code examples
rubychef-infrachef-recipe

Chef : chef-client walks code first before executing it


In a Chef recipe I want to

  1. unzip a file
  2. use one of the files in the zip to iterate over the contents.

The problem I am having is when I run chef-client it fails saying 'No such file or directory' before it has even unzipped the file in step 1

Here is the code of the Provider:

    action :create do
      if @current_resource.exists
        converge_by("Create #{ @current_resource }") do
           unzip('realFileToUnzip','someLocation')  
           do_something_with_file('realFileToOpen')
        end
      end
    end
....

In the same provider file I have a def defined as follows

def unzip(fileToUnzip, unzipToLocation)
  bash "unzip" do
    user "root"
    cwd "/tmp"
    code <<-EOH
        unzip  -o #{fileToUnzip} -d #{unzipToLocation}
    EOH
  end
end

and this def also

def do_something_with_file(fileToConvert)
  ::File.open(fileToConvert, 'r') do |properties_file|
    properties_file.read.each_line do |line|
      puts line
    end
  end
end

It seems that chef-client is walking the code first before executing it. So in the walk through the file is not present as it will not be there until it executes the unzip code.

How can I avoid this?


Solution

  • From Chef Docs:

    Use the ruby_block resource to execute Ruby code during a chef-client run. Ruby code in the ruby_block resource is evaluated with other resources during convergence, whereas Ruby code outside of a ruby_block resource is evaluated before other resources, as the recipe is compiled.

    Then you have to create a ruby_block and insert the code of do_something_with_file into this resource. Maybe you have to make some modifications.

    Good luck!