Chef LWRP - defs/resources execution order

2019-08-05 08:34发布

问题:

I have the following in a LWRP, all it does is exploding an .ear file::

action :expand do
    ear_folder = new_resource.target_folder
    temp_folder = "#{::File.join(ear_folder, 'tmp_folder')}"

    expand_ear(new_resource.source, ear_folder)
    expand_wars(ear_folder,temp_folder)

end

def expand_ear(src,dest)
   bash "unzip EAR" do
     cwd dest
     code <<-EOF
     pwd
     ls -l
     jar -xvf #{src}         
     EOF
   end
end

def explode_wars(src,dest)
    Dir.glob("#{basepath}/*.war") do |file|
           ......... ###crete tmp folder, move .war there then unzip it to 'dest'
        end
end

When I run this /using Vagrant provide/ the output shows that Chef starts 'expand_ear' and 'expand_wars' in parallel. As a consequence the expand_wars def fails to find all .wars /they are still being extracted. I tried making 'expand_ear' boolean and wrapping 'expand_wars' in :

if expand_ear?(src,dest) 
   expand_war 
end

but this yields the same result.???

回答1:

Chef run consists of 2 phases, the compile and execution. During the first phase chef goes through recipes and:

  1. if it sees pure ruby code - it gets executed.
  2. if it sees resource definition - it is compiled and put into resource collection.

Your problem is that code in expand_ear gets compiled - because it's a resource, but the code in explode_wars gets executed straight away - because it's pure ruby. There are 2 possible solutions:

Change your expand_ear to define bash resource dynamically:

res = Chef::Resource::Bash.new "unzip EAR", run_context
res.cwd dest
res.code <<-EOF
  pwd
  ls -l
  jar -xvf #{src}         
  EOF
res.run_action :run

This is pure ruby - and therefore will be executed instead of compiling.

OR put your ruby code in explode_wars into ruby_block resource.

ruby_block do
  block do
    Dir.glob("#{basepath}/*.war") do |file|
       ......... ###crete tmp folder, move .war there then unzip it to 'dest'
    end
  end
end

This way it will be compiled too, and executed only during the 2nd phase.



标签: chef vagrant