From 433d7805113b4ef7729134f119d41f952f14e9cf Mon Sep 17 00:00:00 2001 From: Andrew Schoen Date: Mon, 3 Aug 2015 14:52:49 -0500 Subject: [PATCH] A callback plugin that logs failure messages If the environment variable ANSIBLE_FAILURE_LOG is present then a log of all failures in the playbook will be persisted to the file path given in the ANSIBLE_FAILURE_LOG. Signed-off-by: Andrew Schoen --- .gitignore | 1 + callback_plugins/failure_log.py | 57 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 callback_plugins/failure_log.py diff --git a/.gitignore b/.gitignore index 0f3693c..3a5b30d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.swp virtualenv +*.pyc diff --git a/callback_plugins/failure_log.py b/callback_plugins/failure_log.py new file mode 100644 index 0000000..78ddbfc --- /dev/null +++ b/callback_plugins/failure_log.py @@ -0,0 +1,57 @@ +""" +This callback plugin writes ansible failures to a log as yaml. This way you +can parse the file later and use the ansible failures for other reporting +or logging. + +A log will not be written unless the environment variable ANSIBLE_FAILURE_LOG +is present and contains a path to a file to write the log to. + +NOTE: This plugin was only tested on ansible version 1.9.2 and does not support +v2 style plugins +""" +import yaml +import os +import logging + +log = logging.getLogger(__name__) +# We only want to log if this env var is populated with +# a file path of where the log should live. +fail_log = os.environ.get('ANSIBLE_FAILURE_LOG') +if fail_log: + handler = logging.FileHandler(filename=fail_log) + log.addHandler(handler) + + +def log_failure(host, result): + """ + If the environment variable ANSIBLE_FAILURE_LOG is present + a log of all failures in the playbook will be persisted to + the file path given in ANSIBLE_FAILURE_LOG. + """ + if fail_log: + failure = {"{0}".format(host): dict()} + failure[host] = result + log.error(yaml.safe_dump(failure)) + + +class CallbackModule(object): + """ + This Ansible callback plugin writes task failures to a yaml file. + """ + + def runner_on_failed(self, host, result, ignore_errors=False): + """ + A hook that will be called on every task failure. + """ + + if ignore_errors: + return + + log_failure(host, result) + + def runner_on_unreachable(self, host, result): + """ + A hook that will be called on every task that is unreachable. + """ + + log_failure(host, result) -- 2.39.5