How to add condition on action of a resource block in CHEF?

985 Views Asked by At

I created one resource which has two actions.

Let's say action:A1 and action:A2. Iam able to call them in one single resource block(test) like this :

test 'Testing the actions' do
    action [:a1 ,:a2]
    only_if {::File.exists?"/tmp/action_exist.txt"}
end

It is working fine.But what if I want to add the condition on the action like this

Check condition only for action :A1. and simply run action :A2 irrespective of condition.

I tried like this :

test 'Testing the actions' do
    action [:A1 ,:A2]
    if (action.first=="A1")
            puts "yes"
            only_if {::File.exists?"/tmp/action_exist.txt" }
    end

end

But it's not working. It is executing this condition for both the actions

2

There are 2 best solutions below

0
coderanger On

This is not how Chef works. The resource body isn't a script that is run each action.

0
David M On

It depends on whether the condition is known at compile time. If the condition is known at compile time, you could write something like:

test 'Testing the action' do
  if ::File.exists?('/tmp/action_exist.txt')
    action [:A1, :A2]
  else
    action [:A2]
  end
end

But that's only if your recipes are not fiddling with /tmp/action_exist.txt during the run. If the status of /tmp/action_exist.txt might change during convergence, then you may need to do something fancier. For instance, you could notify the resource to perform :A1 immediately in some resource the precedes the resource. That's not something I have done, so you will probably need to experiment.