EdTed
EdTed

Reputation: 21

Different Only-If Condition as Guard for Chef

Is there a way to use this script (or something which looks approximately the same) as a only_if guard in chef?

#!/bin/bash
application = application_name
if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then  *do something*
fi

I tried the classic way but it either returns nothing so the only_if condition passes by default or it tells me that I can't compare a string with an integer (which is obvious).

execute "script" do
command "my command here"
only_if "$(ps -ef | grep -v grep | grep service_name | wc -l) > 0"

Any ideas or suggestions are appreciated.

Upvotes: 0

Views: 1101

Answers (2)

jayhendren
jayhendren

Reputation: 4511

To answer the question more generally, if you have an arbitrary script you want to use for your only_if or not_if guard, you can do something along these lines:

my_guard_script = File.join Chef::Config[:file_cache_path], 'my_guard_script.sh'

file my_guard_script do
  content <<- EOF
#!/bin/sh

# contents of your script here
EOF
end

resource 'my_awesome_resource' do
  some_parameter 'some_value'
  only_if my_guard_script
end

Warning: I haven't tested this, so there are probably bugs.

Upvotes: 0

coderanger
coderanger

Reputation: 54181

To convert it literally you would need to use the test command, usually aliased as [: only_if "[ $(ps -ef | grep -v grep | grep service_name | wc -l) > 0 ]". But you could also do it somewhat more nicely in Ruby code instead:

only_if { shell_out!('ps -ef').include?('service_name') }

Upvotes: 1

Related Questions