0

I'm running an ansible command ansible-playbook inside a bash script, but when ansible fails for what ever reason, I need the script to detect this and handle the error (eg. output a defined message and exit 1)

I can't seem to fine the best way to still display the output of ansible-playbook command, but capture the output to find if there is an error to then exit the bash script?

This is how an failure/error would be detected based on the output of ansible-playbook. The full output could be ~100 lines.

[0;32m    openstack: PLAY RECAP ***********************************  
[0;32m    openstack: ok=92   changed=73      unreachable=0    failed=1

As you can see from the above, failed=1 indicates a failure, so if failed=[1-9]+ is there, the bash script should exit.

I've tried using cmds like tee, but not having much luck.

5
  • 3
    Doesn't ansible-playbook have a useful exit code? Commented Mar 16, 2016 at 0:00
  • 1
    what happens with ansible-playbook --bad-option; echo statusFromAnsible=$? ? Good luck. Commented Mar 16, 2016 at 0:49
  • @thatotherguy Unfortunately it doesn't Commented Mar 17, 2016 at 9:00
  • whould tee solve your problem ? ansible-playbook test.yml | tee output.log Commented Mar 17, 2016 at 11:16
  • 1
    if ansible-playbook etc | tee /dev/stderr | grep 'failed=[^0]'; then exit 1; fi Commented Mar 17, 2016 at 16:47

2 Answers 2

1

I can't answer the question how to best capture the output of a command and still display it while executing in a bash script.

But here's a very simple alternative. Activate logging in your ansbile.cfg:

log_path=/var/log/ansible.log

Before you start the Ansible run, shred that file. Run Ansible. Then check the logfile for the presence of your pattern.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the good suggestion @udondan, sadly this won't work in our case as the script could be running concurrently, so the log could contain multiple instances of ansible-playbook
0

Here's what I ended up doing (Similar to @thatotherguy suggestion)

My code looks similar to this, but not so crude.

log=logs/$(date +"%s")
ansible-playbook ... | tee $log
# Do some clean up tasks
if grep -q failed=[^0] "$log"; then
  exit 1
  rm $log
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.