adamstrawson
adamstrawson

Reputation: 115

Run command in bash script while output and capture results

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.

Upvotes: 0

Views: 1204

Answers (2)

adamstrawson
adamstrawson

Reputation: 115

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

Upvotes: 0

udondan
udondan

Reputation: 59989

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.

Upvotes: 1

Related Questions