4

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?

1
  • what distribution are you using? on my redhat there is no -c flag for pgrep, so pgrep -fc 'ruby execute.rb' will always return 2, which means "Syntax error"
    – ray
    Nov 22, 2013 at 9:57

2 Answers 2

6

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",
}
2
  • onlyif vs unless .... super useful
    – nandoP
    Nov 22, 2013 at 16:04
  • Hi @SamiLaine, thanks for your answer. I was not aware the unless command checks the shell command exit code. However still it does not work. When I run the command manually, I get an exit status code of 1. However puppet will not run this command even with unless. May there be some other issue with this? Dec 10, 2013 at 15:53
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",
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .