Reputation: 542
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?
Upvotes: 3
Views: 6607
Reputation: 1985
As an explicit, generalized statement: "In order to run, all only_if
s must be true, and all not_if
s 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.
Upvotes: 0
Reputation: 581
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.
Upvotes: 0
Reputation: 54267
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.
Upvotes: 9