sorin
sorin

Reputation: 170390

Can I make ansible no_log default based on ansible verbosity level?

There are lots of ansible modules which have very verbose output by default, like sync, file, and all os_* ones, which had the bad habit of returning huge results on console.

ANSIBLE_VERBOSITY level is useless for these because even level 0 does not remove "results" from the output.

Using alternative output plugins via ANSIBLE_STDOUT_CALLBACK is another lost cause because at this moment none of the existing alternative callbacks had an option to disable these.

Adding no_log: true or smarter alternatives like no_log: result.rc == 0 to each occurrence of spammy module does not scale in practice.

I know that can define no_log: true at playbook level, but this does not allow me to enable logging conditionally.

Upvotes: 3

Views: 5236

Answers (2)

Gert van den Berg
Gert van den Berg

Reputation: 2756

You can template the no_log option based on the verbosity level (which is exposed in ansible_verbosity, at least as of 2.9)

This will supress it for one of the tasks, unless the verbosity is 3 or higher.

- hosts: localhost
  tasks:
  - name: Show verbosity level
    debug:
      var: ansible_verbosity
  - name: Get a list of installed packages
    no_log: "{{ ansible_verbosity < 3 }}"
    package_facts:
      manager: auto

(This should also work play-wide, by combining this with this answer)

Upvotes: 5

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68239

If you want 'clean' solution, you should definitely write a custom callback plugin to reduce amount of output to required level.

But you have an option to use this workaround to conditionally template no_log based on verbosity:

---
- hosts: localhost
  gather_facts: no
  no_log: "{{ verbose_check | default(dict(skipped=true)) | skipped }}"
  vars:
    mydict:
      password: abc
  tasks:
    - debug:
        msg: "Shown only with verbosity > 2"
        verbosity: 3
      register: verbose_check

    - debug:
        var: mydict

debug module has built-in ability to be skipped depending on verbosity level. We can register it's output and define no_log based on it. And because of the fact that Jinja {{...}} expressions are templated when used and not when defined, every following task will evaluate no_log to true or false depending on skipped state our verbose_check.

Upvotes: 3

Related Questions