Linux – puppet onlyif with pgrep does not work

linuxpgreppuppet

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?

Best Answer

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",
}