puppet onlyif with pgrep does not work
I want to use an exec in puppet onlyif its process is NOT running
exec { "execute me":
onlyif => "pgrep -fc 'ruby execute.rb'",
command => "execute me",
}
So on the above case, if the process 'ruby execute.rb' is already running, the exec should not run as
pgrep -fc 'ruby execute.rb' will return 1.
However
The command seems to always run in puppet.
On my linux box when I do pgrep -fc 'ruby execute.rb' I always get a value more than 0.
Is there something wrong with my command?
Solution 1:
Your exec will run only if pgrep returns 0. The pgrep manual page tells us that the exit code for pgrep will be zero (0) only when matching processes are found and it'll return one (1) when there are no matching processes. The puppet documentation on the other hand tells us that parameter onlyif causes the resource to be executed only when command in the parameter returns 0.
Instead of onlyif
you should use parameter unless. That way your exec will only run when your pgrep returns non-zero ie. it doesn't find any matching processes.
exec { "execute me":
unless => "pgrep -fc 'ruby execute.rb'",
command => "execute me",
}
Solution 2:
Have you tried using the full path: /usr/bin/pgrep?
Perhaps the puppet agent cannot find the pgrep command in the onlyif / unless statement. It is also possible to specify the command search path in the exec resource type as attribute path https://docs.puppet.com/puppet/latest/reference/type.html#exec-attribute-path
exec { "execute me":
onlyif => "pgrep -fc 'ruby execute.rb'",
command => "execute me",
path => "/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin",
}