How to Extract Hostname from Ansible Playbook Run [closed]

I need to accomplish following shell script. I trying to extract the HOSTNAME after it runs Successful via Ansible Playbook Run.

I have text file which contains Ansible-Playbook run command to be executed and writing the output into the log file: result.log

Here is what's the "result.log" file looks like

PLAY RECAP *********************************************************************
TESTLINUX01 : ok=6 changed=1 unreachable=0 failed=0

If the failed is "0", Unreachable is "0" and Changed is more then 0, then print the HOSTNAME only. In this case, TESTLINUX01

Thank you for your help.

3

2 Answers

You can use someting like this:

#!/bin/bash
file="result.log"
changed=`grep -Po "changed=\K\d+" $file`
unreachable=`grep -Po "unreachable=\K\d+" $file`
failed=`grep -Po "failed=\K\d+" $file`
if [ $changed -ge 1 -a $unreachable -eq 0 -a $failed -eq 0 ] then cut -s -f1 -d: $file | tr -s ' '
fi

First we extract all necessary values then we compare them with your desired ones, if they where match we print out the host name.

  • grep -Po "changed=\K\d+ returns the number in front of "changed"
  • IF statement:
    • $changed -ge 1 if changed is greater that equal "1"
    • -a and
    • $unreachable -eq 0 unreachable was equal to "0"
    • -a and
    • $failed -eq 0 failed was equal to "0", Then:
  • cut -s -f1 -d: $file | tr -s ' ' prints the hostname
5

Thank you all for replying and providing the solution. Following code works out for me:

cat $file
$file >> $LOGFILE
SUCCESS=`grep "unreachable=0 failed=0" $LOGFILE | awk '{printf "%s ", $1;}'`
echo "Success: $SUCCESS"
FAILURE=`grep -E "unreachable=0 failed=[1-9]" $LOGFILE | awk '{printf "%s ", $1;}'`
echo "Failure: $FAILURE"
Unreachable=`grep -E "unreachable=1 failed=0" $LOGFILE | awk '{printf "%s ", $1;}'`
echo "Unreachable: $Unreachable"

You Might Also Like