Execute the resource block on condition


I would like to execute the below resource block on server, only when the service is not installed/running.

"execute 'Execute a shell' do
command "bash -c 'cd /home/ && chmod 777 /home/rundeck-2.11.3-1.54.GA.noarch && chmod 777 /home/rundeck-config-2.11.3-1.54.GA.noarch && yum install /home/rundeck-2.11.3-1.54.GA.noarch /home/rundeck-config-2.11.3-1.54.GA.noarch -y'"

I have read about guards (only_if and not_if), but not sure how exactly I can use.

A not_if guard will let you set a conditional on when you want to fire off a resource. In your case, you'll want to explicitly say that you're running a bash script.

So it might look something like this:

bash 'do my thing' do
  command "cd /tmp && rm -rf backups"
  not_if "systemctl status mysql"

This works because it's testing the exit code of your systemctl call.

You can try a one-liner to see what's going on with that:
if systemctl status mysql; then echo "Running"; else echo "Not Running"; fi

Replace with a service that isn't (or is, if you're not on a MySQL server) running, to see the difference.

This should get you moving in the right direction.

1 Like