| 1 |
# Copyright (c) Fastly, inc 2016 |
| 2 |
# Copyright (c) 2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
author: Unknown (!UNKNOWN) |
| 10 |
name: selective |
| 11 |
type: stdout |
| 12 |
requirements: |
| 13 |
- set as main display callback |
| 14 |
short_description: Only print certain tasks |
| 15 |
description: |
| 16 |
- This callback only prints tasks that have been tagged with C(print_action) or that have failed. This allows operators |
| 17 |
to focus on the tasks that provide value only. |
| 18 |
- Tasks that are not printed are placed with a C(.). |
| 19 |
- If you increase verbosity all tasks are printed. |
| 20 |
options: |
| 21 |
nocolor: |
| 22 |
default: false |
| 23 |
description: This setting allows suppressing colorizing output. |
| 24 |
env: |
| 25 |
- name: ANSIBLE_NOCOLOR |
| 26 |
- name: ANSIBLE_SELECTIVE_DONT_COLORIZE |
| 27 |
ini: |
| 28 |
- section: defaults |
| 29 |
key: nocolor |
| 30 |
type: boolean |
| 31 |
""" |
| 32 |
|
| 33 |
EXAMPLES = r""" |
| 34 |
- ansible.builtin.debug: msg="This will not be printed" |
| 35 |
- ansible.builtin.debug: msg="But this will" |
| 36 |
tags: [print_action] |
| 37 |
""" |
| 38 |
|
| 39 |
import difflib |
| 40 |
|
| 41 |
from ansible import constants as C |
| 42 |
from ansible.module_utils.common.text.converters import to_text |
| 43 |
from ansible.plugins.callback import CallbackBase |
| 44 |
|
| 45 |
DONT_COLORIZE = False |
| 46 |
COLORS = { |
| 47 |
"normal": "\033[0m", |
| 48 |
"ok": f"\x1b[{C.COLOR_CODES[C.COLOR_OK]}m", # type: ignore |
| 49 |
"bold": "\033[1m", |
| 50 |
"not_so_bold": "\033[1m\033[34m", |
| 51 |
"changed": f"\x1b[{C.COLOR_CODES[C.COLOR_CHANGED]}m", # type: ignore |
| 52 |
"failed": f"\x1b[{C.COLOR_CODES[C.COLOR_ERROR]}m", # type: ignore |
| 53 |
"endc": "\033[0m", |
| 54 |
"skipped": f"\x1b[{C.COLOR_CODES[C.COLOR_SKIP]}m", # type: ignore |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
def dict_diff(prv, nxt): |
| 59 |
"""Return a dict of keys that differ with another config object.""" |
| 60 |
keys = set(list(prv.keys()) + list(nxt.keys())) |
| 61 |
result = {} |
| 62 |
for k in keys: |
| 63 |
if prv.get(k) != nxt.get(k): |
| 64 |
result[k] = (prv.get(k), nxt.get(k)) |
| 65 |
return result |
| 66 |
|
| 67 |
|
| 68 |
def colorize(msg, color): |
| 69 |
"""Given a string add necessary codes to format the string.""" |
| 70 |
if DONT_COLORIZE: |
| 71 |
return msg |
| 72 |
else: |
| 73 |
return f"{COLORS[color]}{msg}{COLORS['endc']}" |
| 74 |
|
| 75 |
|
| 76 |
class CallbackModule(CallbackBase): |
| 77 |
"""selective.py callback plugin.""" |
| 78 |
|
| 79 |
CALLBACK_VERSION = 2.0 |
| 80 |
CALLBACK_TYPE = "stdout" |
| 81 |
CALLBACK_NAME = "community.general.selective" |
| 82 |
|
| 83 |
def __init__(self, display=None): |
| 84 |
"""selective.py callback plugin.""" |
| 85 |
super().__init__(display) |
| 86 |
self.last_skipped = False |
| 87 |
self.last_task_name = None |
| 88 |
self.printed_last_task = False |
| 89 |
|
| 90 |
def set_options(self, task_keys=None, var_options=None, direct=None): |
| 91 |
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct) |
| 92 |
|
| 93 |
global DONT_COLORIZE |
| 94 |
DONT_COLORIZE = self.get_option("nocolor") |
| 95 |
|
| 96 |
def _print_task(self, task_name=None): |
| 97 |
if task_name is None: |
| 98 |
task_name = self.last_task_name |
| 99 |
|
| 100 |
if not self.printed_last_task: |
| 101 |
self.printed_last_task = True |
| 102 |
line_length = 120 |
| 103 |
if self.last_skipped: |
| 104 |
self._display.display("") |
| 105 |
line = f"# {task_name} " |
| 106 |
msg = colorize(f"{line}{'*' * (line_length - len(line))}", "bold") |
| 107 |
self._display.display(msg) |
| 108 |
|
| 109 |
def _indent_text(self, text, indent_level): |
| 110 |
lines = text.splitlines() |
| 111 |
result_lines = [] |
| 112 |
for l in lines: |
| 113 |
result_lines.append(f"{' ' * indent_level}{l}") |
| 114 |
return "\n".join(result_lines) |
| 115 |
|
| 116 |
def _print_diff(self, diff, indent_level): |
| 117 |
if isinstance(diff, dict): |
| 118 |
try: |
| 119 |
diff = "\n".join( |
| 120 |
difflib.unified_diff( |
| 121 |
diff["before"].splitlines(), |
| 122 |
diff["after"].splitlines(), |
| 123 |
fromfile=diff.get("before_header", "new_file"), |
| 124 |
tofile=diff["after_header"], |
| 125 |
) |
| 126 |
) |
| 127 |
except AttributeError: |
| 128 |
diff = dict_diff(diff["before"], diff["after"]) |
| 129 |
if diff: |
| 130 |
diff = colorize(str(diff), "changed") |
| 131 |
self._display.display(self._indent_text(diff, indent_level + 4)) |
| 132 |
|
| 133 |
def _print_host_or_item(self, host_or_item, changed, msg, diff, is_host, error, stdout, stderr): |
| 134 |
if is_host: |
| 135 |
indent_level = 0 |
| 136 |
name = colorize(host_or_item.name, "not_so_bold") |
| 137 |
else: |
| 138 |
indent_level = 4 |
| 139 |
if isinstance(host_or_item, dict): |
| 140 |
if "key" in host_or_item.keys(): |
| 141 |
host_or_item = host_or_item["key"] |
| 142 |
name = colorize(to_text(host_or_item), "bold") |
| 143 |
|
| 144 |
if error: |
| 145 |
color = "failed" |
| 146 |
change_string = colorize("FAILED!!!", color) |
| 147 |
else: |
| 148 |
color = "changed" if changed else "ok" |
| 149 |
change_string = colorize(f"changed={changed}", color) |
| 150 |
|
| 151 |
msg = colorize(msg, color) |
| 152 |
|
| 153 |
line_length = 120 |
| 154 |
spaces = " " * (40 - len(name) - indent_level) |
| 155 |
line = f"{' ' * indent_level} * {name}{spaces}- {change_string}" |
| 156 |
|
| 157 |
if len(msg) < 50: |
| 158 |
line += f" -- {msg}" |
| 159 |
self._display.display(f"{line} {'-' * (line_length - len(line))}---------") |
| 160 |
else: |
| 161 |
self._display.display(f"{line} {'-' * (line_length - len(line))}") |
| 162 |
self._display.display(self._indent_text(msg, indent_level + 4)) |
| 163 |
|
| 164 |
if diff: |
| 165 |
self._print_diff(diff, indent_level) |
| 166 |
if stdout: |
| 167 |
stdout = colorize(stdout, "failed") |
| 168 |
self._display.display(self._indent_text(stdout, indent_level + 4)) |
| 169 |
if stderr: |
| 170 |
stderr = colorize(stderr, "failed") |
| 171 |
self._display.display(self._indent_text(stderr, indent_level + 4)) |
| 172 |
|
| 173 |
def v2_playbook_on_play_start(self, play): |
| 174 |
"""Run on start of the play.""" |
| 175 |
pass |
| 176 |
|
| 177 |
def v2_playbook_on_task_start(self, task, **kwargs): |
| 178 |
"""Run when a task starts.""" |
| 179 |
self.last_task_name = task.get_name() |
| 180 |
self.printed_last_task = False |
| 181 |
|
| 182 |
def _print_task_result(self, result, error=False, **kwargs): |
| 183 |
"""Run when a task finishes correctly.""" |
| 184 |
|
| 185 |
if "print_action" in result._task.tags or error or self._display.verbosity > 1: |
| 186 |
self._print_task() |
| 187 |
self.last_skipped = False |
| 188 |
msg = to_text(result._result.get("msg", "")) or to_text(result._result.get("reason", "")) |
| 189 |
|
| 190 |
stderr = [result._result.get("exception", None), result._result.get("module_stderr", None)] |
| 191 |
stderr = "\n".join([e for e in stderr if e]).strip() |
| 192 |
|
| 193 |
self._print_host_or_item( |
| 194 |
result._host, |
| 195 |
result._result.get("changed", False), |
| 196 |
msg, |
| 197 |
result._result.get("diff", None), |
| 198 |
is_host=True, |
| 199 |
error=error, |
| 200 |
stdout=result._result.get("module_stdout", None), |
| 201 |
stderr=stderr.strip(), |
| 202 |
) |
| 203 |
if "results" in result._result: |
| 204 |
for r in result._result["results"]: |
| 205 |
failed = "failed" in r and r["failed"] |
| 206 |
|
| 207 |
stderr = [r.get("exception", None), r.get("module_stderr", None)] |
| 208 |
stderr = "\n".join([e for e in stderr if e]).strip() |
| 209 |
|
| 210 |
self._print_host_or_item( |
| 211 |
r[r["ansible_loop_var"]], |
| 212 |
r.get("changed", False), |
| 213 |
to_text(r.get("msg", "")), |
| 214 |
r.get("diff", None), |
| 215 |
is_host=False, |
| 216 |
error=failed, |
| 217 |
stdout=r.get("module_stdout", None), |
| 218 |
stderr=stderr.strip(), |
| 219 |
) |
| 220 |
else: |
| 221 |
self.last_skipped = True |
| 222 |
print(".", end="") |
| 223 |
|
| 224 |
def v2_playbook_on_stats(self, stats): |
| 225 |
"""Display info about playbook statistics.""" |
| 226 |
self._display.display("") |
| 227 |
self.printed_last_task = False |
| 228 |
self._print_task("STATS") |
| 229 |
|
| 230 |
hosts = sorted(stats.processed.keys()) |
| 231 |
max_len = max((len(h) for h in hosts), default=0) |
| 232 |
for host in hosts: |
| 233 |
s = stats.summarize(host) |
| 234 |
|
| 235 |
if s["failures"] or s["unreachable"]: |
| 236 |
color = "failed" |
| 237 |
elif s["changed"]: |
| 238 |
color = "changed" |
| 239 |
else: |
| 240 |
color = "ok" |
| 241 |
|
| 242 |
msg = ( |
| 243 |
f"{host.ljust(max_len)} : ok={s['ok']}\tchanged={s['changed']}\tfailed={s['failures']}\t" |
| 244 |
f"unreachable={s['unreachable']}\trescued={s['rescued']}\tignored={s['ignored']}" |
| 245 |
) |
| 246 |
self._display.display(colorize(msg, color)) |
| 247 |
|
| 248 |
def v2_runner_on_skipped(self, result, **kwargs): |
| 249 |
"""Run when a task is skipped.""" |
| 250 |
if self._display.verbosity > 1: |
| 251 |
self._print_task() |
| 252 |
self.last_skipped = False |
| 253 |
|
| 254 |
line_length = 120 |
| 255 |
spaces = " " * (31 - len(result._host.name) - 4) |
| 256 |
|
| 257 |
line = f" * {colorize(result._host.name, 'not_so_bold')}{spaces}- {colorize('skipped', 'skipped')}" |
| 258 |
|
| 259 |
reason = result._result.get("skipped_reason", "") or result._result.get("skip_reason", "") |
| 260 |
if len(reason) < 50: |
| 261 |
line += f" -- {reason}" |
| 262 |
self._display.display(f"{line} {'-' * (line_length - len(line))}---------") |
| 263 |
else: |
| 264 |
self._display.display(f"{line} {'-' * (line_length - len(line))}") |
| 265 |
self._display.display(self._indent_text(reason, 8)) |
| 266 |
self._display.display(reason) |
| 267 |
|
| 268 |
def v2_runner_on_ok(self, result, **kwargs): |
| 269 |
self._print_task_result(result, error=False, **kwargs) |
| 270 |
|
| 271 |
def v2_runner_on_failed(self, result, **kwargs): |
| 272 |
self._print_task_result(result, error=True, **kwargs) |
| 273 |
|
| 274 |
def v2_runner_on_unreachable(self, result, **kwargs): |
| 275 |
self._print_task_result(result, error=True, **kwargs) |
| 276 |
|
| 277 |
v2_playbook_on_handler_task_start = v2_playbook_on_task_start |