From c3ed2144e2585ee7c91761f666767154e299c734 Mon Sep 17 00:00:00 2001 From: Alexei Znamensky <103110+russoz@users.noreply.github.com> Date: Wed, 25 Dec 2024 00:00:10 +1300 Subject: [PATCH] callback plugins: use f-strings (#9321) * callback plugins: use f-strings * add changelog frag * manual change for few occurrences * manual change for few occurrences * adjustment from review * adjustment from review * adjustment from review * Update plugins/callback/splunk.py Co-authored-by: Felix Fontein * replace str templating with JSON templating --------- Co-authored-by: Felix Fontein --- .../fragments/9321-fstr-callback-plugins.yml | 22 +++++ plugins/callback/cgroup_memory_recap.py | 4 +- plugins/callback/context_demo.py | 6 +- plugins/callback/counter_enabled.py | 86 +++++++++---------- plugins/callback/dense.py | 54 ++++++------ plugins/callback/diy.py | 6 +- plugins/callback/elastic.py | 10 +-- plugins/callback/jabber.py | 6 +- plugins/callback/log_plays.py | 19 ++-- plugins/callback/loganalytics.py | 7 +- plugins/callback/logdna.py | 4 +- plugins/callback/logentries.py | 12 +-- plugins/callback/mail.py | 52 +++++------ plugins/callback/nrdp.py | 19 ++-- plugins/callback/opentelemetry.py | 15 ++-- plugins/callback/say.py | 16 ++-- plugins/callback/selective.py | 42 ++++----- plugins/callback/slack.py | 31 ++++--- plugins/callback/splunk.py | 5 +- plugins/callback/timestamp.py | 4 +- plugins/callback/unixy.py | 80 ++++++++--------- plugins/callback/yaml.py | 4 +- 22 files changed, 251 insertions(+), 253 deletions(-) create mode 100644 changelogs/fragments/9321-fstr-callback-plugins.yml diff --git a/changelogs/fragments/9321-fstr-callback-plugins.yml b/changelogs/fragments/9321-fstr-callback-plugins.yml new file mode 100644 index 0000000000..d79d3cbfa0 --- /dev/null +++ b/changelogs/fragments/9321-fstr-callback-plugins.yml @@ -0,0 +1,22 @@ +minor_changes: + - cgroup_memory_recap callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - context_demo callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - counter_enabled callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - dense callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - diy callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - elastic callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - jabber callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - log_plays callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - loganalytics callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - logdna callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - logentries callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - mail callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - nrdp callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - opentelemetry callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - say callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - selective callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - slack callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - splunk callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - timestamp callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - unixy callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). + - yaml callback plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9321). diff --git a/plugins/callback/cgroup_memory_recap.py b/plugins/callback/cgroup_memory_recap.py index 643f0f0b88..e8599aad49 100644 --- a/plugins/callback/cgroup_memory_recap.py +++ b/plugins/callback/cgroup_memory_recap.py @@ -114,7 +114,7 @@ class CallbackModule(CallbackBase): max_results = int(f.read().strip()) / 1024 / 1024 self._display.banner('CGROUP MEMORY RECAP') - self._display.display('Execution Maximum: %0.2fMB\n\n' % max_results) + self._display.display(f'Execution Maximum: {max_results:0.2f}MB\n\n') for task, memory in self.task_results: - self._display.display('%s (%s): %0.2fMB' % (task.get_name(), task._uuid, memory)) + self._display.display(f'{task.get_name()} ({task._uuid}): {memory:0.2f}MB') diff --git a/plugins/callback/context_demo.py b/plugins/callback/context_demo.py index b9558fc064..94dfdf45ad 100644 --- a/plugins/callback/context_demo.py +++ b/plugins/callback/context_demo.py @@ -38,15 +38,15 @@ class CallbackModule(CallbackBase): self.play = None def v2_on_any(self, *args, **kwargs): - self._display.display("--- play: {0} task: {1} ---".format(getattr(self.play, 'name', None), self.task)) + self._display.display(f"--- play: {getattr(self.play, 'name', None)} task: {self.task} ---") self._display.display(" --- ARGS ") for i, a in enumerate(args): - self._display.display(' %s: %s' % (i, a)) + self._display.display(f' {i}: {a}') self._display.display(" --- KWARGS ") for k in kwargs: - self._display.display(' %s: %s' % (k, kwargs[k])) + self._display.display(f' {k}: {kwargs[k]}') def v2_playbook_on_play_start(self, play): self.play = play diff --git a/plugins/callback/counter_enabled.py b/plugins/callback/counter_enabled.py index 27adc97a6c..9bb1df07d4 100644 --- a/plugins/callback/counter_enabled.py +++ b/plugins/callback/counter_enabled.py @@ -71,7 +71,7 @@ class CallbackModule(CallbackBase): if not name: msg = u"play" else: - msg = u"PLAY [%s]" % name + msg = f"PLAY [{name}]" self._play = play @@ -91,25 +91,17 @@ class CallbackModule(CallbackBase): for host in hosts: stat = stats.summarize(host) - self._display.display(u"%s : %s %s %s %s %s %s" % ( - hostcolor(host, stat), - colorize(u'ok', stat['ok'], C.COLOR_OK), - colorize(u'changed', stat['changed'], C.COLOR_CHANGED), - colorize(u'unreachable', stat['unreachable'], C.COLOR_UNREACHABLE), - colorize(u'failed', stat['failures'], C.COLOR_ERROR), - colorize(u'rescued', stat['rescued'], C.COLOR_OK), - colorize(u'ignored', stat['ignored'], C.COLOR_WARN)), + self._display.display( + f"{hostcolor(host, stat)} : {colorize(u'ok', stat['ok'], C.COLOR_OK)} {colorize(u'changed', stat['changed'], C.COLOR_CHANGED)} " + f"{colorize(u'unreachable', stat['unreachable'], C.COLOR_UNREACHABLE)} {colorize(u'failed', stat['failures'], C.COLOR_ERROR)} " + f"{colorize(u'rescued', stat['rescued'], C.COLOR_OK)} {colorize(u'ignored', stat['ignored'], C.COLOR_WARN)}", screen_only=True ) - self._display.display(u"%s : %s %s %s %s %s %s" % ( - hostcolor(host, stat, False), - colorize(u'ok', stat['ok'], None), - colorize(u'changed', stat['changed'], None), - colorize(u'unreachable', stat['unreachable'], None), - colorize(u'failed', stat['failures'], None), - colorize(u'rescued', stat['rescued'], None), - colorize(u'ignored', stat['ignored'], None)), + self._display.display( + f"{hostcolor(host, stat, False)} : {colorize(u'ok', stat['ok'], None)} {colorize(u'changed', stat['changed'], None)} " + f"{colorize(u'unreachable', stat['unreachable'], None)} {colorize(u'failed', stat['failures'], None)} " + f"{colorize(u'rescued', stat['rescued'], None)} {colorize(u'ignored', stat['ignored'], None)}", log_only=True ) @@ -124,12 +116,14 @@ class CallbackModule(CallbackBase): for k in sorted(stats.custom.keys()): if k == '_run': continue - self._display.display('\t%s: %s' % (k, self._dump_results(stats.custom[k], indent=1).replace('\n', ''))) + _custom_stats = self._dump_results(stats.custom[k], indent=1).replace('\n', '') + self._display.display(f'\t{k}: {_custom_stats}') # print per run custom stats if '_run' in stats.custom: self._display.display("", screen_only=True) - self._display.display('\tRUN: %s' % self._dump_results(stats.custom['_run'], indent=1).replace('\n', '')) + _custom_stats_run = self._dump_results(stats.custom['_run'], indent=1).replace('\n', '') + self._display.display(f'\tRUN: {_custom_stats_run}') self._display.display("", screen_only=True) def v2_playbook_on_task_start(self, task, is_conditional): @@ -143,13 +137,13 @@ class CallbackModule(CallbackBase): # that they can secure this if they feel that their stdout is insecure # (shoulder surfing, logging stdout straight to a file, etc). if not task.no_log and C.DISPLAY_ARGS_TO_STDOUT: - args = ', '.join(('%s=%s' % a for a in task.args.items())) - args = ' %s' % args - self._display.banner("TASK %d/%d [%s%s]" % (self._task_counter, self._task_total, task.get_name().strip(), args)) + args = ', '.join(('{k}={v}' for k, v in task.args.items())) + args = f' {args}' + self._display.banner(f"TASK {self._task_counter}/{self._task_total} [{task.get_name().strip()}{args}]") if self._display.verbosity >= 2: path = task.get_path() if path: - self._display.display("task path: %s" % path, color=C.COLOR_DEBUG) + self._display.display(f"task path: {path}", color=C.COLOR_DEBUG) self._host_counter = self._previous_batch_total self._task_counter += 1 @@ -166,15 +160,15 @@ class CallbackModule(CallbackBase): return elif result._result.get('changed', False): if delegated_vars: - msg = "changed: %d/%d [%s -> %s]" % (self._host_counter, self._host_total, result._host.get_name(), delegated_vars['ansible_host']) + msg = f"changed: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> {delegated_vars['ansible_host']}]" else: - msg = "changed: %d/%d [%s]" % (self._host_counter, self._host_total, result._host.get_name()) + msg = f"changed: {self._host_counter}/{self._host_total} [{result._host.get_name()}]" color = C.COLOR_CHANGED else: if delegated_vars: - msg = "ok: %d/%d [%s -> %s]" % (self._host_counter, self._host_total, result._host.get_name(), delegated_vars['ansible_host']) + msg = f"ok: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> {delegated_vars['ansible_host']}]" else: - msg = "ok: %d/%d [%s]" % (self._host_counter, self._host_total, result._host.get_name()) + msg = f"ok: {self._host_counter}/{self._host_total} [{result._host.get_name()}]" color = C.COLOR_OK self._handle_warnings(result._result) @@ -185,7 +179,7 @@ class CallbackModule(CallbackBase): self._clean_results(result._result, result._task.action) if self._run_is_verbose(result): - msg += " => %s" % (self._dump_results(result._result),) + msg += f" => {self._dump_results(result._result)}" self._display.display(msg, color=color) def v2_runner_on_failed(self, result, ignore_errors=False): @@ -206,14 +200,16 @@ class CallbackModule(CallbackBase): else: if delegated_vars: - self._display.display("fatal: %d/%d [%s -> %s]: FAILED! => %s" % (self._host_counter, self._host_total, - result._host.get_name(), delegated_vars['ansible_host'], - self._dump_results(result._result)), - color=C.COLOR_ERROR) + self._display.display( + f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> " + f"{delegated_vars['ansible_host']}]: FAILED! => {self._dump_results(result._result)}", + color=C.COLOR_ERROR + ) else: - self._display.display("fatal: %d/%d [%s]: FAILED! => %s" % (self._host_counter, self._host_total, - result._host.get_name(), self._dump_results(result._result)), - color=C.COLOR_ERROR) + self._display.display( + f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()}]: FAILED! => {self._dump_results(result._result)}", + color=C.COLOR_ERROR + ) if ignore_errors: self._display.display("...ignoring", color=C.COLOR_SKIP) @@ -231,9 +227,9 @@ class CallbackModule(CallbackBase): if result._task.loop and 'results' in result._result: self._process_items(result) else: - msg = "skipping: %d/%d [%s]" % (self._host_counter, self._host_total, result._host.get_name()) + msg = f"skipping: {self._host_counter}/{self._host_total} [{result._host.get_name()}]" if self._run_is_verbose(result): - msg += " => %s" % self._dump_results(result._result) + msg += f" => {self._dump_results(result._result)}" self._display.display(msg, color=C.COLOR_SKIP) def v2_runner_on_unreachable(self, result): @@ -244,11 +240,13 @@ class CallbackModule(CallbackBase): delegated_vars = result._result.get('_ansible_delegated_vars', None) if delegated_vars: - self._display.display("fatal: %d/%d [%s -> %s]: UNREACHABLE! => %s" % (self._host_counter, self._host_total, - result._host.get_name(), delegated_vars['ansible_host'], - self._dump_results(result._result)), - color=C.COLOR_UNREACHABLE) + self._display.display( + f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> " + f"{delegated_vars['ansible_host']}]: UNREACHABLE! => {self._dump_results(result._result)}", + color=C.COLOR_UNREACHABLE + ) else: - self._display.display("fatal: %d/%d [%s]: UNREACHABLE! => %s" % (self._host_counter, self._host_total, - result._host.get_name(), self._dump_results(result._result)), - color=C.COLOR_UNREACHABLE) + self._display.display( + f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()}]: UNREACHABLE! => {self._dump_results(result._result)}", + color=C.COLOR_UNREACHABLE + ) diff --git a/plugins/callback/dense.py b/plugins/callback/dense.py index 490705fd27..e0419644ef 100644 --- a/plugins/callback/dense.py +++ b/plugins/callback/dense.py @@ -195,7 +195,7 @@ class CallbackModule(CallbackModule_default): self.disabled = True def __del__(self): - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") def _add_host(self, result, status): name = result._host.get_name() @@ -252,7 +252,7 @@ class CallbackModule(CallbackModule_default): def _display_progress(self, result=None): # Always rewrite the complete line sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.nolinewrap + vt100.underline) - sys.stdout.write('%s %d:' % (self.type, self.count[self.type])) + sys.stdout.write(f'{self.type} {self.count[self.type]}:') sys.stdout.write(vt100.reset) sys.stdout.flush() @@ -260,7 +260,7 @@ class CallbackModule(CallbackModule_default): for name in self.hosts: sys.stdout.write(' ') if self.hosts[name].get('delegate', None): - sys.stdout.write(self.hosts[name]['delegate'] + '>') + sys.stdout.write(f"{self.hosts[name]['delegate']}>") sys.stdout.write(colors[self.hosts[name]['state']] + name + vt100.reset) sys.stdout.flush() @@ -274,8 +274,8 @@ class CallbackModule(CallbackModule_default): if not self.shown_title: self.shown_title = True sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.underline) - sys.stdout.write('%s %d: %s' % (self.type, self.count[self.type], self.task.get_name().strip())) - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f'{self.type} {self.count[self.type]}: {self.task.get_name().strip()}') + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") sys.stdout.flush() else: sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline) @@ -284,7 +284,7 @@ class CallbackModule(CallbackModule_default): def _display_results(self, result, status): # Leave the previous task on screen (as it has changes/errors) if self._display.verbosity == 0 and self.keep: - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") else: sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline) self.keep = False @@ -309,15 +309,15 @@ class CallbackModule(CallbackModule_default): if result._task.loop and 'results' in result._result: self._process_items(result) else: - sys.stdout.write(colors[status] + status + ': ') + sys.stdout.write(f"{colors[status] + status}: ") delegated_vars = result._result.get('_ansible_delegated_vars', None) if delegated_vars: - sys.stdout.write(vt100.reset + result._host.get_name() + '>' + colors[status] + delegated_vars['ansible_host']) + sys.stdout.write(f"{vt100.reset + result._host.get_name()}>{colors[status]}{delegated_vars['ansible_host']}") else: sys.stdout.write(result._host.get_name()) - sys.stdout.write(': ' + dump + '\n') + sys.stdout.write(f": {dump}\n") sys.stdout.write(vt100.reset + vt100.save + vt100.clearline) sys.stdout.flush() @@ -327,7 +327,7 @@ class CallbackModule(CallbackModule_default): def v2_playbook_on_play_start(self, play): # Leave the previous task on screen (as it has changes/errors) if self._display.verbosity == 0 and self.keep: - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline + vt100.bold) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}{vt100.bold}") else: sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.bold) @@ -341,14 +341,14 @@ class CallbackModule(CallbackModule_default): name = play.get_name().strip() if not name: name = 'unnamed' - sys.stdout.write('PLAY %d: %s' % (self.count['play'], name.upper())) - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"PLAY {self.count['play']}: {name.upper()}") + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") sys.stdout.flush() def v2_playbook_on_task_start(self, task, is_conditional): # Leave the previous task on screen (as it has changes/errors) if self._display.verbosity == 0 and self.keep: - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline + vt100.underline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}{vt100.underline}") else: # Do not clear line, since we want to retain the previous output sys.stdout.write(vt100.restore + vt100.reset + vt100.underline) @@ -365,14 +365,14 @@ class CallbackModule(CallbackModule_default): self.count['task'] += 1 # Write the next task on screen (behind the prompt is the previous output) - sys.stdout.write('%s %d.' % (self.type, self.count[self.type])) + sys.stdout.write(f'{self.type} {self.count[self.type]}.') sys.stdout.write(vt100.reset) sys.stdout.flush() def v2_playbook_on_handler_task_start(self, task): # Leave the previous task on screen (as it has changes/errors) if self._display.verbosity == 0 and self.keep: - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline + vt100.underline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}{vt100.underline}") else: sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.underline) @@ -388,7 +388,7 @@ class CallbackModule(CallbackModule_default): self.count[self.type] += 1 # Write the next task on screen (behind the prompt is the previous output) - sys.stdout.write('%s %d.' % (self.type, self.count[self.type])) + sys.stdout.write(f'{self.type} {self.count[self.type]}.') sys.stdout.write(vt100.reset) sys.stdout.flush() @@ -451,13 +451,13 @@ class CallbackModule(CallbackModule_default): def v2_playbook_on_no_hosts_remaining(self): if self._display.verbosity == 0 and self.keep: - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") else: sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline) self.keep = False - sys.stdout.write(vt100.white + vt100.redbg + 'NO MORE HOSTS LEFT') - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"{vt100.white + vt100.redbg}NO MORE HOSTS LEFT") + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") sys.stdout.flush() def v2_playbook_on_include(self, included_file): @@ -465,7 +465,7 @@ class CallbackModule(CallbackModule_default): def v2_playbook_on_stats(self, stats): if self._display.verbosity == 0 and self.keep: - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") else: sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline) @@ -476,22 +476,16 @@ class CallbackModule(CallbackModule_default): sys.stdout.write(vt100.bold + vt100.underline) sys.stdout.write('SUMMARY') - sys.stdout.write(vt100.restore + vt100.reset + '\n' + vt100.save + vt100.clearline) + sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}") sys.stdout.flush() hosts = sorted(stats.processed.keys()) for h in hosts: t = stats.summarize(h) self._display.display( - u"%s : %s %s %s %s %s %s" % ( - hostcolor(h, t), - colorize(u'ok', t['ok'], C.COLOR_OK), - colorize(u'changed', t['changed'], C.COLOR_CHANGED), - colorize(u'unreachable', t['unreachable'], C.COLOR_UNREACHABLE), - colorize(u'failed', t['failures'], C.COLOR_ERROR), - colorize(u'rescued', t['rescued'], C.COLOR_OK), - colorize(u'ignored', t['ignored'], C.COLOR_WARN), - ), + f"{hostcolor(h, t)} : {colorize(u'ok', t['ok'], C.COLOR_OK)} {colorize(u'changed', t['changed'], C.COLOR_CHANGED)} " + f"{colorize(u'unreachable', t['unreachable'], C.COLOR_UNREACHABLE)} {colorize(u'failed', t['failures'], C.COLOR_ERROR)} " + f"{colorize(u'rescued', t['rescued'], C.COLOR_OK)} {colorize(u'ignored', t['ignored'], C.COLOR_WARN)}", screen_only=True ) diff --git a/plugins/callback/diy.py b/plugins/callback/diy.py index cf9369e4b4..e3cda4ac7c 100644 --- a/plugins/callback/diy.py +++ b/plugins/callback/diy.py @@ -828,9 +828,9 @@ class CallbackModule(Default): _callback_options = ['msg', 'msg_color'] for option in _callback_options: - _option_name = '%s_%s' % (_callback_type, option) + _option_name = f'{_callback_type}_{option}' _option_template = variables.get( - self.DIY_NS + "_" + _option_name, + f"{self.DIY_NS}_{_option_name}", self.get_option(_option_name) ) _ret.update({option: self._template( @@ -867,7 +867,7 @@ class CallbackModule(Default): handler=None, result=None, stats=None, remove_attr_ref_loop=True): def _get_value(obj, attr=None, method=None): if attr: - return getattr(obj, attr, getattr(obj, "_" + attr, None)) + return getattr(obj, attr, getattr(obj, f"_{attr}", None)) if method: _method = getattr(obj, method) diff --git a/plugins/callback/elastic.py b/plugins/callback/elastic.py index 0c94d1ba33..9b5942d962 100644 --- a/plugins/callback/elastic.py +++ b/plugins/callback/elastic.py @@ -118,7 +118,7 @@ class TaskData: if host.uuid in self.host_data: if host.status == 'included': # concatenate task include output from multiple items - host.result = '%s\n%s' % (self.host_data[host.uuid].result, host.result) + host.result = f'{self.host_data[host.uuid].result}\n{host.result}' else: return @@ -166,7 +166,7 @@ class ElasticSource(object): args = None if not task.no_log and not hide_task_arguments: - args = ', '.join(('%s=%s' % a for a in task.args.items())) + args = ', '.join((f'{k}={v}' for k, v in task.args.items())) tasks_data[uuid] = TaskData(uuid, name, path, play_name, action, args) @@ -225,7 +225,7 @@ class ElasticSource(object): def create_span_data(self, apm_cli, task_data, host_data): """ create the span with the given TaskData and HostData """ - name = '[%s] %s: %s' % (host_data.name, task_data.play, task_data.name) + name = f'[{host_data.name}] {task_data.play}: {task_data.name}' message = "success" status = "success" @@ -259,7 +259,7 @@ class ElasticSource(object): "ansible.task.host.status": host_data.status}) as span: span.outcome = status if 'failure' in status: - exception = AnsibleRuntimeError(message="{0}: {1} failed with error message {2}".format(task_data.action, name, enriched_error_message)) + exception = AnsibleRuntimeError(message=f"{task_data.action}: {name} failed with error message {enriched_error_message}") apm_cli.capture_exception(exc_info=(type(exception), exception, exception.__traceback__), handled=True) def init_apm_client(self, apm_server_url, apm_service_name, apm_verify_server_cert, apm_secret_token, apm_api_key): @@ -288,7 +288,7 @@ class ElasticSource(object): message = result.get('msg', 'failed') exception = result.get('exception') stderr = result.get('stderr') - return ('message: "{0}"\nexception: "{1}"\nstderr: "{2}"').format(message, exception, stderr) + return f"message: \"{message}\"\nexception: \"{exception}\"\nstderr: \"{stderr}\"" class CallbackModule(CallbackBase): diff --git a/plugins/callback/jabber.py b/plugins/callback/jabber.py index 302687b708..f63f07b4f5 100644 --- a/plugins/callback/jabber.py +++ b/plugins/callback/jabber.py @@ -102,7 +102,7 @@ class CallbackModule(CallbackBase): """Display Playbook and play start messages""" self.play = play name = play.name - self.send_msg("Ansible starting play: %s" % (name)) + self.send_msg(f"Ansible starting play: {name}") def playbook_on_stats(self, stats): name = self.play @@ -118,7 +118,7 @@ class CallbackModule(CallbackBase): if failures or unreachable: out = self.debug - self.send_msg("%s: Failures detected \n%s \nHost: %s\n Failed at:\n%s" % (name, self.task, h, out)) + self.send_msg(f"{name}: Failures detected \n{self.task} \nHost: {h}\n Failed at:\n{out}") else: out = self.debug - self.send_msg("Great! \n Playbook %s completed:\n%s \n Last task debug:\n %s" % (name, s, out)) + self.send_msg(f"Great! \n Playbook {name} completed:\n{s} \n Last task debug:\n {out}") diff --git a/plugins/callback/log_plays.py b/plugins/callback/log_plays.py index daa88bcc11..190e1c60c4 100644 --- a/plugins/callback/log_plays.py +++ b/plugins/callback/log_plays.py @@ -57,7 +57,10 @@ class CallbackModule(CallbackBase): CALLBACK_NEEDS_WHITELIST = True TIME_FORMAT = "%b %d %Y %H:%M:%S" - MSG_FORMAT = "%(now)s - %(playbook)s - %(task_name)s - %(task_action)s - %(category)s - %(data)s\n\n" + + @staticmethod + def _make_msg(now, playbook, task_name, task_action, category, data): + return f"{now} - {playbook} - {task_name} - {task_action} - {category} - {data}\n\n" def __init__(self): @@ -82,22 +85,12 @@ class CallbackModule(CallbackBase): invocation = data.pop('invocation', None) data = json.dumps(data, cls=AnsibleJSONEncoder) if invocation is not None: - data = json.dumps(invocation) + " => %s " % data + data = f"{json.dumps(invocation)} => {data} " path = os.path.join(self.log_folder, result._host.get_name()) now = time.strftime(self.TIME_FORMAT, time.localtime()) - msg = to_bytes( - self.MSG_FORMAT - % dict( - now=now, - playbook=self.playbook, - task_name=result._task.name, - task_action=result._task.action, - category=category, - data=data, - ) - ) + msg = to_bytes(self._make_msg(now, self.playbook, result._task.name, result._task.action, category, data)) with open(path, "ab") as fd: fd.write(msg) diff --git a/plugins/callback/loganalytics.py b/plugins/callback/loganalytics.py index fd1b2772c4..98ceb1e7a3 100644 --- a/plugins/callback/loganalytics.py +++ b/plugins/callback/loganalytics.py @@ -84,18 +84,17 @@ class AzureLogAnalyticsSource(object): def __build_signature(self, date, workspace_id, shared_key, content_length): # Build authorisation signature for Azure log analytics API call - sigs = "POST\n{0}\napplication/json\nx-ms-date:{1}\n/api/logs".format( - str(content_length), date) + sigs = f"POST\n{content_length}\napplication/json\nx-ms-date:{date}\n/api/logs" utf8_sigs = sigs.encode('utf-8') decoded_shared_key = base64.b64decode(shared_key) hmac_sha256_sigs = hmac.new( decoded_shared_key, utf8_sigs, digestmod=hashlib.sha256).digest() encoded_hash = base64.b64encode(hmac_sha256_sigs).decode('utf-8') - signature = "SharedKey {0}:{1}".format(workspace_id, encoded_hash) + signature = f"SharedKey {workspace_id}:{encoded_hash}" return signature def __build_workspace_url(self, workspace_id): - return "https://{0}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01".format(workspace_id) + return f"https://{workspace_id}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01" def __rfc1123date(self): return now().strftime('%a, %d %b %Y %H:%M:%S GMT') diff --git a/plugins/callback/logdna.py b/plugins/callback/logdna.py index fc9a81ac8a..cbf9df4b1c 100644 --- a/plugins/callback/logdna.py +++ b/plugins/callback/logdna.py @@ -73,7 +73,7 @@ except ImportError: # Getting MAC Address of system: def get_mac(): - mac = "%012x" % getnode() + mac = f"{getnode():012x}" return ":".join(map(lambda index: mac[index:index + 2], range(int(len(mac) / 2)))) @@ -161,7 +161,7 @@ class CallbackModule(CallbackBase): if ninvalidKeys > 0: for key in invalidKeys: del meta[key] - meta['__errors'] = 'These keys have been sanitized: ' + ', '.join(invalidKeys) + meta['__errors'] = f"These keys have been sanitized: {', '.join(invalidKeys)}" return meta def sanitizeJSON(self, data): diff --git a/plugins/callback/logentries.py b/plugins/callback/logentries.py index c1271543ad..bc8b1cb5bd 100644 --- a/plugins/callback/logentries.py +++ b/plugins/callback/logentries.py @@ -153,7 +153,7 @@ class PlainTextSocketAppender(object): self.open_connection() return except Exception as e: - self._display.vvvv(u"Unable to connect to Logentries: %s" % to_text(e)) + self._display.vvvv(f"Unable to connect to Logentries: {to_text(e)}") root_delay *= 2 if root_delay > self.MAX_DELAY: @@ -162,7 +162,7 @@ class PlainTextSocketAppender(object): wait_for = root_delay + random.uniform(0, root_delay) try: - self._display.vvvv("sleeping %s before retry" % wait_for) + self._display.vvvv(f"sleeping {wait_for} before retry") time.sleep(wait_for) except KeyboardInterrupt: raise @@ -249,7 +249,7 @@ class CallbackModule(CallbackBase): self.use_tls = self.get_option('use_tls') self.flatten = self.get_option('flatten') except KeyError as e: - self._display.warning(u"Missing option for Logentries callback plugin: %s" % to_text(e)) + self._display.warning(f"Missing option for Logentries callback plugin: {to_text(e)}") self.disabled = True try: @@ -268,10 +268,10 @@ class CallbackModule(CallbackBase): if not self.disabled: if self.use_tls: - self._display.vvvv("Connecting to %s:%s with TLS" % (self.api_url, self.api_tls_port)) + self._display.vvvv(f"Connecting to {self.api_url}:{self.api_tls_port} with TLS") self._appender = TLSSocketAppender(display=self._display, LE_API=self.api_url, LE_TLS_PORT=self.api_tls_port) else: - self._display.vvvv("Connecting to %s:%s" % (self.api_url, self.api_port)) + self._display.vvvv(f"Connecting to {self.api_url}:{self.api_port}") self._appender = PlainTextSocketAppender(display=self._display, LE_API=self.api_url, LE_PORT=self.api_port) self._appender.reopen_connection() @@ -284,7 +284,7 @@ class CallbackModule(CallbackBase): def emit(self, record): msg = record.rstrip('\n') - msg = "{0} {1}".format(self.token, msg) + msg = f"{self.token} {msg}" self._appender.put(msg) self._display.vvvv("Sent event to logentries") diff --git a/plugins/callback/mail.py b/plugins/callback/mail.py index 1b847ea34c..2e26fe84eb 100644 --- a/plugins/callback/mail.py +++ b/plugins/callback/mail.py @@ -135,14 +135,14 @@ class CallbackModule(CallbackBase): if self.bcc: bcc_addresses = email.utils.getaddresses(self.bcc) - content = 'Date: %s\n' % email.utils.formatdate() - content += 'From: %s\n' % email.utils.formataddr(sender_address) + content = f'Date: {email.utils.formatdate()}\n' + content += f'From: {email.utils.formataddr(sender_address)}\n' if self.to: - content += 'To: %s\n' % ', '.join([email.utils.formataddr(pair) for pair in to_addresses]) + content += f"To: {', '.join([email.utils.formataddr(pair) for pair in to_addresses])}\n" if self.cc: - content += 'Cc: %s\n' % ', '.join([email.utils.formataddr(pair) for pair in cc_addresses]) - content += 'Message-ID: %s\n' % email.utils.make_msgid(domain=self.get_option('message_id_domain')) - content += 'Subject: %s\n\n' % subject.strip() + content += f"Cc: {', '.join([email.utils.formataddr(pair) for pair in cc_addresses])}\n" + content += f"Message-ID: {email.utils.make_msgid(domain=self.get_option('message_id_domain'))}\n" + content += f'Subject: {subject.strip()}\n\n' content += body addresses = to_addresses @@ -159,23 +159,22 @@ class CallbackModule(CallbackBase): smtp.quit() def subject_msg(self, multiline, failtype, linenr): - return '%s: %s' % (failtype, multiline.strip('\r\n').splitlines()[linenr]) + msg = multiline.strip('\r\n').splitlines()[linenr] + return f'{failtype}: {msg}' def indent(self, multiline, indent=8): return re.sub('^', ' ' * indent, multiline, flags=re.MULTILINE) def body_blob(self, multiline, texttype): ''' Turn some text output in a well-indented block for sending in a mail body ''' - intro = 'with the following %s:\n\n' % texttype - blob = '' - for line in multiline.strip('\r\n').splitlines(): - blob += '%s\n' % line - return intro + self.indent(blob) + '\n' + intro = f'with the following {texttype}:\n\n' + blob = "\n".join(multiline.strip('\r\n').splitlines()) + return f"{intro}{self.indent(blob)}\n" def mail_result(self, result, failtype): host = result._host.get_name() if not self.sender: - self.sender = '"Ansible: %s" ' % host + self.sender = f'"Ansible: {host}" ' # Add subject if self.itembody: @@ -191,31 +190,32 @@ class CallbackModule(CallbackBase): elif result._result.get('exception'): # Unrelated exceptions are added to output :-/ subject = self.subject_msg(result._result['exception'], failtype, -1) else: - subject = '%s: %s' % (failtype, result._task.name or result._task.action) + subject = f'{failtype}: {result._task.name or result._task.action}' # Make playbook name visible (e.g. in Outlook/Gmail condensed view) - body = 'Playbook: %s\n' % os.path.basename(self.playbook._file_name) + body = f'Playbook: {os.path.basename(self.playbook._file_name)}\n' if result._task.name: - body += 'Task: %s\n' % result._task.name - body += 'Module: %s\n' % result._task.action - body += 'Host: %s\n' % host + body += f'Task: {result._task.name}\n' + body += f'Module: {result._task.action}\n' + body += f'Host: {host}\n' body += '\n' # Add task information (as much as possible) body += 'The following task failed:\n\n' if 'invocation' in result._result: - body += self.indent('%s: %s\n' % (result._task.action, json.dumps(result._result['invocation']['module_args'], indent=4))) + body += self.indent(f"{result._task.action}: {json.dumps(result._result['invocation']['module_args'], indent=4)}\n") elif result._task.name: - body += self.indent('%s (%s)\n' % (result._task.name, result._task.action)) + body += self.indent(f'{result._task.name} ({result._task.action})\n') else: - body += self.indent('%s\n' % result._task.action) + body += self.indent(f'{result._task.action}\n') body += '\n' # Add item / message if self.itembody: body += self.itembody elif result._result.get('failed_when_result') is True: - body += "due to the following condition:\n\n" + self.indent('failed_when:\n- ' + '\n- '.join(result._task.failed_when)) + '\n\n' + fail_cond = self.indent('failed_when:\n- ' + '\n- '.join(result._task.failed_when)) + body += f"due to the following condition:\n\n{fail_cond}\n\n" elif result._result.get('msg'): body += self.body_blob(result._result['msg'], 'message') @@ -228,13 +228,13 @@ class CallbackModule(CallbackBase): body += self.body_blob(result._result['exception'], 'exception') if result._result.get('warnings'): for i in range(len(result._result.get('warnings'))): - body += self.body_blob(result._result['warnings'][i], 'exception %d' % (i + 1)) + body += self.body_blob(result._result['warnings'][i], f'exception {i + 1}') if result._result.get('deprecations'): for i in range(len(result._result.get('deprecations'))): - body += self.body_blob(result._result['deprecations'][i], 'exception %d' % (i + 1)) + body += self.body_blob(result._result['deprecations'][i], f'exception {i + 1}') body += 'and a complete dump of the error:\n\n' - body += self.indent('%s: %s' % (failtype, json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4))) + body += self.indent(f'{failtype}: {json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4)}') self.mail(subject=subject, body=body) @@ -257,4 +257,4 @@ class CallbackModule(CallbackBase): def v2_runner_item_on_failed(self, result): # Pass item information to task failure self.itemsubject = result._result['msg'] - self.itembody += self.body_blob(json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4), "failed item dump '%(item)s'" % result._result) + self.itembody += self.body_blob(json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4), f"failed item dump '{result._result['item']}'") diff --git a/plugins/callback/nrdp.py b/plugins/callback/nrdp.py index 62f4a89ec8..b937049dc3 100644 --- a/plugins/callback/nrdp.py +++ b/plugins/callback/nrdp.py @@ -132,10 +132,10 @@ class CallbackModule(CallbackBase): xmldata = "\n" xmldata += "\n" xmldata += "\n" - xmldata += "%s\n" % self.hostname - xmldata += "%s\n" % self.servicename - xmldata += "%d\n" % state - xmldata += "%s\n" % msg + xmldata += f"{self.hostname}\n" + xmldata += f"{self.servicename}\n" + xmldata += f"{state}\n" + xmldata += f"{msg}\n" xmldata += "\n" xmldata += "\n" @@ -152,7 +152,7 @@ class CallbackModule(CallbackBase): validate_certs=self.validate_nrdp_certs) return response.read() except Exception as ex: - self._display.warning("NRDP callback cannot send result {0}".format(ex)) + self._display.warning(f"NRDP callback cannot send result {ex}") def v2_playbook_on_play_start(self, play): ''' @@ -170,17 +170,16 @@ class CallbackModule(CallbackBase): critical = warning = 0 for host in hosts: stat = stats.summarize(host) - gstats += "'%s_ok'=%d '%s_changed'=%d \ - '%s_unreachable'=%d '%s_failed'=%d " % \ - (host, stat['ok'], host, stat['changed'], - host, stat['unreachable'], host, stat['failures']) + gstats += ( + f"'{host}_ok'={stat['ok']} '{host}_changed'={stat['changed']} '{host}_unreachable'={stat['unreachable']} '{host}_failed'={stat['failures']} " + ) # Critical when failed tasks or unreachable host critical += stat['failures'] critical += stat['unreachable'] # Warning when changed tasks warning += stat['changed'] - msg = "%s | %s" % (name, gstats) + msg = f"{name} | {gstats}" if critical: # Send Critical self._send_nrdp(self.CRITICAL, msg) diff --git a/plugins/callback/opentelemetry.py b/plugins/callback/opentelemetry.py index 8dc627c214..44c563019c 100644 --- a/plugins/callback/opentelemetry.py +++ b/plugins/callback/opentelemetry.py @@ -209,7 +209,7 @@ class TaskData: if host.uuid in self.host_data: if host.status == 'included': # concatenate task include output from multiple items - host.result = '%s\n%s' % (self.host_data[host.uuid].result, host.result) + host.result = f'{self.host_data[host.uuid].result}\n{host.result}' else: return @@ -347,7 +347,7 @@ class OpenTelemetrySource(object): def update_span_data(self, task_data, host_data, span, disable_logs, disable_attributes_in_logs): """ update the span with the given TaskData and HostData """ - name = '[%s] %s: %s' % (host_data.name, task_data.play, task_data.name) + name = f'[{host_data.name}] {task_data.play}: {task_data.name}' message = 'success' res = {} @@ -470,7 +470,7 @@ class OpenTelemetrySource(object): def get_error_message_from_results(results, action): for result in results: if result.get('failed', False): - return ('{0}({1}) - {2}').format(action, result.get('item', 'none'), OpenTelemetrySource.get_error_message(result)) + return f"{action}({result.get('item', 'none')}) - {OpenTelemetrySource.get_error_message(result)}" @staticmethod def _last_line(text): @@ -482,14 +482,14 @@ class OpenTelemetrySource(object): message = result.get('msg', 'failed') exception = result.get('exception') stderr = result.get('stderr') - return ('message: "{0}"\nexception: "{1}"\nstderr: "{2}"').format(message, exception, stderr) + return f"message: \"{message}\"\nexception: \"{exception}\"\nstderr: \"{stderr}\"" @staticmethod def enrich_error_message_from_results(results, action): message = "" for result in results: if result.get('failed', False): - message = ('{0}({1}) - {2}\n{3}').format(action, result.get('item', 'none'), OpenTelemetrySource.enrich_error_message(result), message) + message = f"{action}({result.get('item', 'none')}) - {OpenTelemetrySource.enrich_error_message(result)}\n{message}" return message @@ -535,8 +535,9 @@ class CallbackModule(CallbackBase): environment_variable = self.get_option('enable_from_environment') if environment_variable is not None and os.environ.get(environment_variable, 'false').lower() != 'true': self.disabled = True - self._display.warning("The `enable_from_environment` option has been set and {0} is not enabled. " - "Disabling the `opentelemetry` callback plugin.".format(environment_variable)) + self._display.warning( + f"The `enable_from_environment` option has been set and {environment_variable} is not enabled. Disabling the `opentelemetry` callback plugin." + ) self.hide_task_arguments = self.get_option('hide_task_arguments') diff --git a/plugins/callback/say.py b/plugins/callback/say.py index 9d96ad74d9..357f84ae08 100644 --- a/plugins/callback/say.py +++ b/plugins/callback/say.py @@ -50,7 +50,7 @@ class CallbackModule(CallbackBase): self.synthesizer = get_bin_path('say') if platform.system() != 'Darwin': # 'say' binary available, it might be GNUstep tool which doesn't support 'voice' parameter - self._display.warning("'say' executable found but system is '%s': ignoring voice parameter" % platform.system()) + self._display.warning(f"'say' executable found but system is '{platform.system()}': ignoring voice parameter") else: self.FAILED_VOICE = 'Zarvox' self.REGULAR_VOICE = 'Trinoids' @@ -69,7 +69,7 @@ class CallbackModule(CallbackBase): # ansible will not call any callback if disabled is set to True if not self.synthesizer: self.disabled = True - self._display.warning("Unable to find either 'say' or 'espeak' executable, plugin %s disabled" % os.path.basename(__file__)) + self._display.warning(f"Unable to find either 'say' or 'espeak' executable, plugin {os.path.basename(__file__)} disabled") def say(self, msg, voice): cmd = [self.synthesizer, msg] @@ -78,7 +78,7 @@ class CallbackModule(CallbackBase): subprocess.call(cmd) def runner_on_failed(self, host, res, ignore_errors=False): - self.say("Failure on host %s" % host, self.FAILED_VOICE) + self.say(f"Failure on host {host}", self.FAILED_VOICE) def runner_on_ok(self, host, res): self.say("pew", self.LASER_VOICE) @@ -87,13 +87,13 @@ class CallbackModule(CallbackBase): self.say("pew", self.LASER_VOICE) def runner_on_unreachable(self, host, res): - self.say("Failure on host %s" % host, self.FAILED_VOICE) + self.say(f"Failure on host {host}", self.FAILED_VOICE) def runner_on_async_ok(self, host, res, jid): self.say("pew", self.LASER_VOICE) def runner_on_async_failed(self, host, res, jid): - self.say("Failure on host %s" % host, self.FAILED_VOICE) + self.say(f"Failure on host {host}", self.FAILED_VOICE) def playbook_on_start(self): self.say("Running Playbook", self.REGULAR_VOICE) @@ -103,15 +103,15 @@ class CallbackModule(CallbackBase): def playbook_on_task_start(self, name, is_conditional): if not is_conditional: - self.say("Starting task: %s" % name, self.REGULAR_VOICE) + self.say(f"Starting task: {name}", self.REGULAR_VOICE) else: - self.say("Notifying task: %s" % name, self.REGULAR_VOICE) + self.say(f"Notifying task: {name}", self.REGULAR_VOICE) def playbook_on_setup(self): self.say("Gathering facts", self.REGULAR_VOICE) def playbook_on_play_start(self, name): - self.say("Starting play: %s" % name, self.HAPPY_VOICE) + self.say(f"Starting play: {name}", self.HAPPY_VOICE) def playbook_on_stats(self, stats): self.say("Play complete", self.HAPPY_VOICE) diff --git a/plugins/callback/selective.py b/plugins/callback/selective.py index 0696757837..3cea24ff1a 100644 --- a/plugins/callback/selective.py +++ b/plugins/callback/selective.py @@ -48,13 +48,13 @@ from ansible.module_utils.common.text.converters import to_text DONT_COLORIZE = False COLORS = { 'normal': '\033[0m', - 'ok': '\033[{0}m'.format(C.COLOR_CODES[C.COLOR_OK]), + 'ok': f'\x1b[{C.COLOR_CODES[C.COLOR_OK]}m', 'bold': '\033[1m', 'not_so_bold': '\033[1m\033[34m', - 'changed': '\033[{0}m'.format(C.COLOR_CODES[C.COLOR_CHANGED]), - 'failed': '\033[{0}m'.format(C.COLOR_CODES[C.COLOR_ERROR]), + 'changed': f'\x1b[{C.COLOR_CODES[C.COLOR_CHANGED]}m', + 'failed': f'\x1b[{C.COLOR_CODES[C.COLOR_ERROR]}m', 'endc': '\033[0m', - 'skipped': '\033[{0}m'.format(C.COLOR_CODES[C.COLOR_SKIP]), + 'skipped': f'\x1b[{C.COLOR_CODES[C.COLOR_SKIP]}m', } @@ -73,7 +73,7 @@ def colorize(msg, color): if DONT_COLORIZE: return msg else: - return '{0}{1}{2}'.format(COLORS[color], msg, COLORS['endc']) + return f"{COLORS[color]}{msg}{COLORS['endc']}" class CallbackModule(CallbackBase): @@ -106,15 +106,15 @@ class CallbackModule(CallbackBase): line_length = 120 if self.last_skipped: print() - line = "# {0} ".format(task_name) - msg = colorize("{0}{1}".format(line, '*' * (line_length - len(line))), 'bold') + line = f"# {task_name} " + msg = colorize(f"{line}{'*' * (line_length - len(line))}", 'bold') print(msg) def _indent_text(self, text, indent_level): lines = text.splitlines() result_lines = [] for l in lines: - result_lines.append("{0}{1}".format(' ' * indent_level, l)) + result_lines.append(f"{' ' * indent_level}{l}") return '\n'.join(result_lines) def _print_diff(self, diff, indent_level): @@ -147,19 +147,19 @@ class CallbackModule(CallbackBase): change_string = colorize('FAILED!!!', color) else: color = 'changed' if changed else 'ok' - change_string = colorize("changed={0}".format(changed), color) + change_string = colorize(f"changed={changed}", color) msg = colorize(msg, color) line_length = 120 spaces = ' ' * (40 - len(name) - indent_level) - line = "{0} * {1}{2}- {3}".format(' ' * indent_level, name, spaces, change_string) + line = f"{' ' * indent_level} * {name}{spaces}- {change_string}" if len(msg) < 50: - line += ' -- {0}'.format(msg) - print("{0} {1}---------".format(line, '-' * (line_length - len(line)))) + line += f' -- {msg}' + print(f"{line} {'-' * (line_length - len(line))}---------") else: - print("{0} {1}".format(line, '-' * (line_length - len(line)))) + print(f"{line} {'-' * (line_length - len(line))}") print(self._indent_text(msg, indent_level + 4)) if diff: @@ -239,8 +239,10 @@ class CallbackModule(CallbackBase): else: color = 'ok' - msg = '{0} : ok={1}\tchanged={2}\tfailed={3}\tunreachable={4}\trescued={5}\tignored={6}'.format( - host, s['ok'], s['changed'], s['failures'], s['unreachable'], s['rescued'], s['ignored']) + msg = ( + f"{host} : ok={s['ok']}\tchanged={s['changed']}\tfailed={s['failures']}\tunreachable=" + f"{s['unreachable']}\trescued={s['rescued']}\tignored={s['ignored']}" + ) print(colorize(msg, color)) def v2_runner_on_skipped(self, result, **kwargs): @@ -252,17 +254,15 @@ class CallbackModule(CallbackBase): line_length = 120 spaces = ' ' * (31 - len(result._host.name) - 4) - line = " * {0}{1}- {2}".format(colorize(result._host.name, 'not_so_bold'), - spaces, - colorize("skipped", 'skipped'),) + line = f" * {colorize(result._host.name, 'not_so_bold')}{spaces}- {colorize('skipped', 'skipped')}" reason = result._result.get('skipped_reason', '') or \ result._result.get('skip_reason', '') if len(reason) < 50: - line += ' -- {0}'.format(reason) - print("{0} {1}---------".format(line, '-' * (line_length - len(line)))) + line += f' -- {reason}' + print(f"{line} {'-' * (line_length - len(line))}---------") else: - print("{0} {1}".format(line, '-' * (line_length - len(line)))) + print(f"{line} {'-' * (line_length - len(line))}") print(self._indent_text(reason, 8)) print(reason) diff --git a/plugins/callback/slack.py b/plugins/callback/slack.py index 2a995992ee..0e58628c35 100644 --- a/plugins/callback/slack.py +++ b/plugins/callback/slack.py @@ -138,14 +138,13 @@ class CallbackModule(CallbackBase): headers=headers) return response.read() except Exception as e: - self._display.warning(u'Could not submit message to Slack: %s' % - to_text(e)) + self._display.warning(f'Could not submit message to Slack: {to_text(e)}') def v2_playbook_on_start(self, playbook): self.playbook_name = os.path.basename(playbook._file_name) title = [ - '*Playbook initiated* (_%s_)' % self.guid + f'*Playbook initiated* (_{self.guid}_)' ] invocation_items = [] @@ -156,23 +155,23 @@ class CallbackModule(CallbackBase): subset = context.CLIARGS['subset'] inventory = [os.path.abspath(i) for i in context.CLIARGS['inventory']] - invocation_items.append('Inventory: %s' % ', '.join(inventory)) + invocation_items.append(f"Inventory: {', '.join(inventory)}") if tags and tags != ['all']: - invocation_items.append('Tags: %s' % ', '.join(tags)) + invocation_items.append(f"Tags: {', '.join(tags)}") if skip_tags: - invocation_items.append('Skip Tags: %s' % ', '.join(skip_tags)) + invocation_items.append(f"Skip Tags: {', '.join(skip_tags)}") if subset: - invocation_items.append('Limit: %s' % subset) + invocation_items.append(f'Limit: {subset}') if extra_vars: - invocation_items.append('Extra Vars: %s' % - ' '.join(extra_vars)) + invocation_items.append(f"Extra Vars: {' '.join(extra_vars)}") - title.append('by *%s*' % context.CLIARGS['remote_user']) + title.append(f"by *{context.CLIARGS['remote_user']}*") - title.append('\n\n*%s*' % self.playbook_name) + title.append(f'\n\n*{self.playbook_name}*') msg_items = [' '.join(title)] if invocation_items: - msg_items.append('```\n%s\n```' % '\n'.join(invocation_items)) + _inv_item = '\n'.join(invocation_items) + msg_items.append(f'```\n{_inv_item}\n```') msg = '\n'.join(msg_items) @@ -192,8 +191,8 @@ class CallbackModule(CallbackBase): def v2_playbook_on_play_start(self, play): """Display Play start messages""" - name = play.name or 'Play name not specified (%s)' % play._uuid - msg = '*Starting play* (_%s_)\n\n*%s*' % (self.guid, name) + name = play.name or f'Play name not specified ({play._uuid})' + msg = f'*Starting play* (_{self.guid}_)\n\n*{name}*' attachments = [ { 'fallback': msg, @@ -228,7 +227,7 @@ class CallbackModule(CallbackBase): attachments = [] msg_items = [ - '*Playbook Complete* (_%s_)' % self.guid + f'*Playbook Complete* (_{self.guid}_)' ] if failures or unreachable: color = 'danger' @@ -237,7 +236,7 @@ class CallbackModule(CallbackBase): color = 'good' msg_items.append('\n*Success!*') - msg_items.append('```\n%s\n```' % t) + msg_items.append(f'```\n{t}\n```') msg = '\n'.join(msg_items) diff --git a/plugins/callback/splunk.py b/plugins/callback/splunk.py index b2ce48de25..966170594c 100644 --- a/plugins/callback/splunk.py +++ b/plugins/callback/splunk.py @@ -153,15 +153,14 @@ class SplunkHTTPCollectorSource(object): data['ansible_result'] = result._result # This wraps the json payload in and outer json event needed by Splunk - jsondata = json.dumps(data, cls=AnsibleJSONEncoder, sort_keys=True) - jsondata = '{"event":' + jsondata + "}" + jsondata = json.dumps({"event": data}, cls=AnsibleJSONEncoder, sort_keys=True) open_url( url, jsondata, headers={ 'Content-type': 'application/json', - 'Authorization': 'Splunk ' + authtoken + 'Authorization': f"Splunk {authtoken}" }, method='POST', validate_certs=validate_certs diff --git a/plugins/callback/timestamp.py b/plugins/callback/timestamp.py index 07cd8d239c..d8737b9e4c 100644 --- a/plugins/callback/timestamp.py +++ b/plugins/callback/timestamp.py @@ -85,7 +85,7 @@ def banner(self, msg, color=None, cows=True): msg = to_text(msg) if self.b_cowsay and cows: try: - self.banner_cowsay("%s @ %s" % (msg, timestamp)) + self.banner_cowsay(f"{msg} @ {timestamp}") return except OSError: self.warning("somebody cleverly deleted cowsay or something during the PB run. heh.") @@ -98,7 +98,7 @@ def banner(self, msg, color=None, cows=True): if star_len <= 3: star_len = 3 stars = "*" * star_len - self.display("\n%s %s %s" % (msg, stars, timestamp), color=color) + self.display(f"\n{msg} {stars} {timestamp}", color=color) class CallbackModule(Default): diff --git a/plugins/callback/unixy.py b/plugins/callback/unixy.py index 4908202c23..de0c79088b 100644 --- a/plugins/callback/unixy.py +++ b/plugins/callback/unixy.py @@ -67,24 +67,24 @@ class CallbackModule(CallbackModule_default): def _process_result_output(self, result, msg): task_host = result._host.get_name() - task_result = "%s %s" % (task_host, msg) + task_result = f"{task_host} {msg}" if self._run_is_verbose(result): - task_result = "%s %s: %s" % (task_host, msg, self._dump_results(result._result, indent=4)) + task_result = f"{task_host} {msg}: {self._dump_results(result._result, indent=4)}" return task_result if self.delegated_vars: task_delegate_host = self.delegated_vars['ansible_host'] - task_result = "%s -> %s %s" % (task_host, task_delegate_host, msg) + task_result = f"{task_host} -> {task_delegate_host} {msg}" if result._result.get('msg') and result._result.get('msg') != "All items completed": - task_result += " | msg: " + to_text(result._result.get('msg')) + task_result += f" | msg: {to_text(result._result.get('msg'))}" if result._result.get('stdout'): - task_result += " | stdout: " + result._result.get('stdout') + task_result += f" | stdout: {result._result.get('stdout')}" if result._result.get('stderr'): - task_result += " | stderr: " + result._result.get('stderr') + task_result += f" | stderr: {result._result.get('stderr')}" return task_result @@ -92,28 +92,28 @@ class CallbackModule(CallbackModule_default): self._get_task_display_name(task) if self.task_display_name is not None: if task.check_mode and self.get_option('check_mode_markers'): - self._display.display("%s (check mode)..." % self.task_display_name) + self._display.display(f"{self.task_display_name} (check mode)...") else: - self._display.display("%s..." % self.task_display_name) + self._display.display(f"{self.task_display_name}...") def v2_playbook_on_handler_task_start(self, task): self._get_task_display_name(task) if self.task_display_name is not None: if task.check_mode and self.get_option('check_mode_markers'): - self._display.display("%s (via handler in check mode)... " % self.task_display_name) + self._display.display(f"{self.task_display_name} (via handler in check mode)... ") else: - self._display.display("%s (via handler)... " % self.task_display_name) + self._display.display(f"{self.task_display_name} (via handler)... ") def v2_playbook_on_play_start(self, play): name = play.get_name().strip() if play.check_mode and self.get_option('check_mode_markers'): if name and play.hosts: - msg = u"\n- %s (in check mode) on hosts: %s -" % (name, ",".join(play.hosts)) + msg = f"\n- {name} (in check mode) on hosts: {','.join(play.hosts)} -" else: msg = u"- check mode -" else: if name and play.hosts: - msg = u"\n- %s on hosts: %s -" % (name, ",".join(play.hosts)) + msg = f"\n- {name} on hosts: {','.join(play.hosts)} -" else: msg = u"---" @@ -126,7 +126,7 @@ class CallbackModule(CallbackModule_default): msg = "skipped" task_result = self._process_result_output(result, msg) - self._display.display(" " + task_result, display_color) + self._display.display(f" {task_result}", display_color) else: return @@ -136,10 +136,10 @@ class CallbackModule(CallbackModule_default): msg = "failed" item_value = self._get_item_label(result._result) if item_value: - msg += " | item: %s" % (item_value,) + msg += f" | item: {item_value}" task_result = self._process_result_output(result, msg) - self._display.display(" " + task_result, display_color, stderr=self.get_option('display_failed_stderr')) + self._display.display(f" {task_result}", display_color, stderr=self.get_option('display_failed_stderr')) def v2_runner_on_ok(self, result, msg="ok", display_color=C.COLOR_OK): self._preprocess_result(result) @@ -149,13 +149,13 @@ class CallbackModule(CallbackModule_default): msg = "done" item_value = self._get_item_label(result._result) if item_value: - msg += " | item: %s" % (item_value,) + msg += f" | item: {item_value}" display_color = C.COLOR_CHANGED task_result = self._process_result_output(result, msg) - self._display.display(" " + task_result, display_color) + self._display.display(f" {task_result}", display_color) elif self.get_option('display_ok_hosts'): task_result = self._process_result_output(result, msg) - self._display.display(" " + task_result, display_color) + self._display.display(f" {task_result}", display_color) def v2_runner_item_on_skipped(self, result): self.v2_runner_on_skipped(result) @@ -173,7 +173,7 @@ class CallbackModule(CallbackModule_default): display_color = C.COLOR_UNREACHABLE task_result = self._process_result_output(result, msg) - self._display.display(" " + task_result, display_color, stderr=self.get_option('display_failed_stderr')) + self._display.display(f" {task_result}", display_color, stderr=self.get_option('display_failed_stderr')) def v2_on_file_diff(self, result): if result._task.loop and 'results' in result._result: @@ -195,25 +195,17 @@ class CallbackModule(CallbackModule_default): # TODO how else can we display these? t = stats.summarize(h) - self._display.display(u" %s : %s %s %s %s %s %s" % ( - hostcolor(h, t), - colorize(u'ok', t['ok'], C.COLOR_OK), - colorize(u'changed', t['changed'], C.COLOR_CHANGED), - colorize(u'unreachable', t['unreachable'], C.COLOR_UNREACHABLE), - colorize(u'failed', t['failures'], C.COLOR_ERROR), - colorize(u'rescued', t['rescued'], C.COLOR_OK), - colorize(u'ignored', t['ignored'], C.COLOR_WARN)), + self._display.display( + f" {hostcolor(h, t)} : {colorize(u'ok', t['ok'], C.COLOR_OK)} {colorize(u'changed', t['changed'], C.COLOR_CHANGED)} " + f"{colorize(u'unreachable', t['unreachable'], C.COLOR_UNREACHABLE)} {colorize(u'failed', t['failures'], C.COLOR_ERROR)} " + f"{colorize(u'rescued', t['rescued'], C.COLOR_OK)} {colorize(u'ignored', t['ignored'], C.COLOR_WARN)}", screen_only=True ) - self._display.display(u" %s : %s %s %s %s %s %s" % ( - hostcolor(h, t, False), - colorize(u'ok', t['ok'], None), - colorize(u'changed', t['changed'], None), - colorize(u'unreachable', t['unreachable'], None), - colorize(u'failed', t['failures'], None), - colorize(u'rescued', t['rescued'], None), - colorize(u'ignored', t['ignored'], None)), + self._display.display( + f" {hostcolor(h, t, False)} : {colorize(u'ok', t['ok'], None)} {colorize(u'changed', t['changed'], None)} " + f"{colorize(u'unreachable', t['unreachable'], None)} {colorize(u'failed', t['failures'], None)} {colorize(u'rescued', t['rescued'], None)} " + f"{colorize(u'ignored', t['ignored'], None)}", log_only=True ) if stats.custom and self.get_option('show_custom_stats'): @@ -223,12 +215,14 @@ class CallbackModule(CallbackModule_default): for k in sorted(stats.custom.keys()): if k == '_run': continue - self._display.display('\t%s: %s' % (k, self._dump_results(stats.custom[k], indent=1).replace('\n', ''))) + stat_val = self._dump_results(stats.custom[k], indent=1).replace('\n', '') + self._display.display(f'\t{k}: {stat_val}') # print per run custom stats if '_run' in stats.custom: self._display.display("", screen_only=True) - self._display.display('\tRUN: %s' % self._dump_results(stats.custom['_run'], indent=1).replace('\n', '')) + stat_val_run = self._dump_results(stats.custom['_run'], indent=1).replace('\n', '') + self._display.display(f'\tRUN: {stat_val_run}') self._display.display("", screen_only=True) def v2_playbook_on_no_hosts_matched(self): @@ -239,23 +233,23 @@ class CallbackModule(CallbackModule_default): def v2_playbook_on_start(self, playbook): if context.CLIARGS['check'] and self.get_option('check_mode_markers'): - self._display.display("Executing playbook %s in check mode" % basename(playbook._file_name)) + self._display.display(f"Executing playbook {basename(playbook._file_name)} in check mode") else: - self._display.display("Executing playbook %s" % basename(playbook._file_name)) + self._display.display(f"Executing playbook {basename(playbook._file_name)}") # show CLI arguments if self._display.verbosity > 3: if context.CLIARGS.get('args'): - self._display.display('Positional arguments: %s' % ' '.join(context.CLIARGS['args']), + self._display.display(f"Positional arguments: {' '.join(context.CLIARGS['args'])}", color=C.COLOR_VERBOSE, screen_only=True) for argument in (a for a in context.CLIARGS if a != 'args'): val = context.CLIARGS[argument] if val: - self._display.vvvv('%s: %s' % (argument, val)) + self._display.vvvv(f'{argument}: {val}') def v2_runner_retry(self, result): - msg = " Retrying... (%d of %d)" % (result._result['attempts'], result._result['retries']) + msg = f" Retrying... ({result._result['attempts']} of {result._result['retries']})" if self._run_is_verbose(result): - msg += "Result was: %s" % self._dump_results(result._result) + msg += f"Result was: {self._dump_results(result._result)}" self._display.display(msg, color=C.COLOR_DEBUG) diff --git a/plugins/callback/yaml.py b/plugins/callback/yaml.py index e41f69ec53..1daf4572d5 100644 --- a/plugins/callback/yaml.py +++ b/plugins/callback/yaml.py @@ -113,11 +113,11 @@ class CallbackModule(Default): # put changed and skipped into a header line if 'changed' in abridged_result: - dumped += 'changed=' + str(abridged_result['changed']).lower() + ' ' + dumped += f"changed={str(abridged_result['changed']).lower()} " del abridged_result['changed'] if 'skipped' in abridged_result: - dumped += 'skipped=' + str(abridged_result['skipped']).lower() + ' ' + dumped += f"skipped={str(abridged_result['skipped']).lower()} " del abridged_result['skipped'] # if we already have stdout, we don't need stdout_lines