Ansibleのコールバックプラグイン
プレイブックの最後にchangedになったタスク名とホストを表示する
change_tasks_summary.py
from ansible.plugins.callback import CallbackBase
from ansible.utils.color import stringc
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'changed_tasks_and_hosts_summary'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
self.changed_tasks = {}
self.current_task_name = None
def v2_playbook_on_task_start(self, task, is_conditional):
self.current_task_name = task.get_name().strip()
def v2_runner_on_ok(self, result, **kwargs):
if result.is_changed():
host_name = result._host.get_name()
if self.current_task_name not in self.changed_tasks:
self.changed_tasks[self.current_task_name] = []
# ループを使っている場合
if 'results' in result._result:
for res in result._result['results']:
if res.get('changed', False):
item = res.get('item')
# 表示形式を変更
host_info = f"changed: [{host_name}] => (item={item})"
self.changed_tasks[self.current_task_name].append(host_info)
else:
# ループを使っていない場合
if result._result.get('changed', False):
# 表示形式を変更
host_info = f"changed: [{host_name}]"
self.changed_tasks[self.current_task_name].append(host_info)
def v2_playbook_on_stats(self, stats):
self._display.banner("Changed Tasks and Hosts Summary")
for task_name, host_infos in self.changed_tasks.items():
self._display.display(f"TASK: [{task_name}]")
for host_info in host_infos:
changed_text = stringc(f"changed: [{host_info}]", 'yellow')
self._display.display(changed_text)