From 1b8aa423a63f53936cbcdfe9a5f6201088383227 Mon Sep 17 00:00:00 2001 From: Simon Li Date: Fri, 23 Sep 2016 18:20:41 +0100 Subject: [PATCH] Return non-zero error code if no hosts match This is useful when running ansible-playbook automatically, since failure to mat ch a host may mean there's an incorrect hostname or groupname somewhere --- ansible/ansible.cfg | 3 ++ .../callback/error_if_no_hosts_match.py | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 ansible/plugins/callback/error_if_no_hosts_match.py diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg index 62a1ef2cb..e7b3f64ac 100644 --- a/ansible/ansible.cfg +++ b/ansible/ansible.cfg @@ -26,6 +26,9 @@ inventory_ignore_extensions = ~, .orig, .bak, .ini, .retry, .pyc, .pyo, .html, . # Helps determine what's running slowly callback_whitelist = profile_tasks +# Additional plugins +callback_plugins = ./plugins/callback + # Performance options [ssh_connection] pipelining = True diff --git a/ansible/plugins/callback/error_if_no_hosts_match.py b/ansible/plugins/callback/error_if_no_hosts_match.py new file mode 100644 index 000000000..554ffba5b --- /dev/null +++ b/ansible/plugins/callback/error_if_no_hosts_match.py @@ -0,0 +1,39 @@ +# https://gist.github.com/jjshoe/ace3070906e5bc5cc432 +# https://github.com/ansible/ansible/pull/14742 +# https://github.com/ansible/ansible/issues/14693 + +# Make coding more python3-ish + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import time +import sys + +from ansible.plugins.callback import CallbackBase + + +class CallbackModule(CallbackBase): + """ + This callback module exits with non-zero if no hosts match + """ + CALLBACK_VERSION = 2.0 + CALLBACK_TYPE = 'aggregate' + CALLBACK_NAME = 'no_hosts_match_exit_non_zero' + CALLBACK_NEEDS_WHITELIST = False + + def __init__(self): + super(CallbackModule, self).__init__() + + def playbook_on_stats(self, stats): + found_stats = False + + for key in ['ok', 'failures', 'dark', 'changed', 'skipped']: + if len(getattr(stats, key)) > 0: + found_stats = True + break + + if found_stats == False: + print('ERROR: No hosts matched') + sys.exit(10)