3

I'm confused about the logic order of only_if and not_if in Chef's resource model.

In the following example, assuming a file called /tmp/foo containing the word bar:

execute "rm /tmp/foo" do
    action :run
    only_if "ls /tmp/foo"
    not_if "grep bar /tmp/foo"
end

What happens? Are only_if and not_if exclusive? AND? OR? Which comes first? Why?

3 Answers 3

9

The are run in the order given in the code. The internals of each method basically boils down to @guards << Guard.new(*args) so they track order implicitly. Both clauses must "pass" for the action the run. In general this is a bad idea as it is super hard to read, if you must then leave a very very good comment.

0

In general programming terms, "only_if" is similar to "if" and "not_if" is similar to unless (or if !)

So it is always recommended to have either one of the gaurd check in your resource.

For example:

Below code will be creating the user "adam", if the user does not exists:

not_if 'grep adam /etc/passwd', :user => 'adam'

Below code will be creating foo.txt, only if the directory "/tmp" is exists:

file '/tmp/foo.txt' do
  action :create
  only_if { ::Dir.exist?("/tmp") }
end

Also please refer the Chef documentation for "Gaurds" to get further clarity.

0

As an explicit, generalized statement: "In order to run, all only_ifs must be true, and all not_ifs must be false."

As an example, consider this code:

node.force_default['A'] = true
node.force_default['B'] = true
node.force_default['C'] = false
node.force_default['D'] = false

log 'message' do
  message 'This has run'
  level :error
  only_if { node['A'] }
  only_if { node['B'] }
  not_if { node['C'] }
  not_if { node['D'] }
end

It will print 'This has run'. However, if any of A, B, C or D change, then it will be skipped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.