0
votes

When executing a playbook, I'm trying to report on Unreachable hosts:

PLAY RECAP *********************************************************************************************************************
testinstance01                   : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0   
testinstance02                   : ok=8    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

I looked at creating a ping task, however I noticed that Ansible is clever enough to see that a host is Unreachable and continue on regardless. I figured that it will have this detail stored as metadata or in facts and I wondered how to extract/access this detail?

The overall idea, being I can fire this audit playbook, weekly in the early hours and I'll get results from the online hosts as well as a list of hosts that were Unreachable.

1

1 Answers

2
votes

The unreachable information is available to an Ansible callback plugin, using either the v2_runner_on_unreachable or v2_playbook_on_stats methods. One option is to write your own callback plugin; something as simple as the following might work. We inherit from the default callback plugin and override the v2_playbook_on_stats method to produce a JSON summary:

import json

from ansible.plugins.callback.default import CallbackModule
from ansible import constants as C  # NOQA


class CallbackModule(CallbackModule):
    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'stdout'
    CALLBACK_NAME = 'summary'

    # This avoids errors caused by weird Ansible options handling
    def v2_runner_on_start(self, host, task):
        pass

    def v2_playbook_on_stats(self, stats):
        hosts = sorted(stats.processed.keys())
        summary = {}
        for h in hosts:
            t = stats.summarize(h)
            summary[h] = t

        with open('summary.json', 'w') as fd:
            json.dump(summary, fd, indent=2)

        super(CallbackModule, self).v2_playbook_on_stats(stats)

If you put this in callback_plugins/summary.py, and then configure your ansible.cfg to include:

[defaults]
stdout_callback = summary

You'll get output like this in summary.json:

{
  "node0": {
    "ok": 1,
    "failures": 0,
    "unreachable": 0,
    "changed": 0,
    "skipped": 0,
    "rescued": 0,
    "ignored": 0
  },
  "node1": {
    "ok": 0,
    "failures": 0,
    "unreachable": 1,
    "changed": 0,
    "skipped": 0,
    "rescued": 0,
    "ignored": 0
  }
}