File: tree.py

package info (click to toggle)
ansible-core 2.19.0~beta6-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 32,628 kB
  • sloc: python: 180,313; cs: 4,929; sh: 4,601; xml: 34; makefile: 21
file content (96 lines) | stat: -rw-r--r-- 3,619 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# (c) 2012-2014, Ansible, Inc
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import annotations

DOCUMENTATION = """
    name: tree
    type: notification
    requirements:
      - invoked in the command line
    short_description: Save host events to files
    version_added: "2.0"
    options:
        directory:
            version_added: '2.11'
            description: directory that will contain the per host JSON files. Also set by the C(--tree) option when using adhoc.
            ini:
                - section: callback_tree
                  key: directory
            env:
                - name: ANSIBLE_CALLBACK_TREE_DIR
            default: "~/.ansible/tree"
            type: path
    description:
        - "This callback is used by the Ansible (adhoc) command line option C(-t|--tree)."
        - This produces a JSON dump of events in a directory, a file for each host, the directory used MUST be passed as a command line option.
"""

import os

from ansible.constants import TREE_DIR
from ansible.executor.task_result import CallbackTaskResult
from ansible.module_utils.common.text.converters import to_bytes
from ansible.plugins.callback import CallbackBase
from ansible.utils.path import makedirs_safe, unfrackpath
from ansible.module_utils._internal import _deprecator


class CallbackModule(CallbackBase):
    """
    This callback puts results into a host specific file in a directory in json format.
    """

    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'aggregate'
    CALLBACK_NAME = 'tree'
    CALLBACK_NEEDS_ENABLED = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._display.deprecated(  # pylint: disable=ansible-deprecated-unnecessary-collection-name
            msg='The tree callback plugin is deprecated.',
            version='2.23',
            deprecator=_deprecator.ANSIBLE_CORE_DEPRECATOR,  # entire plugin being removed; this improves the messaging
        )

    def set_options(self, task_keys=None, var_options=None, direct=None):
        """ override to set self.tree """

        super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)

        if TREE_DIR:
            # TREE_DIR comes from the CLI option --tree, only available for adhoc
            self.tree = unfrackpath(TREE_DIR)
        else:
            self.tree = self.get_option('directory')

    def write_tree_file(self, hostname, buf):
        """ write something into treedir/hostname """

        buf = to_bytes(buf)
        try:
            makedirs_safe(self.tree)
        except OSError as ex:
            self._display.error_as_warning(f"Unable to access or create the configured directory {self.tree!r}.", exception=ex)

        try:
            path = to_bytes(os.path.join(self.tree, hostname))
            with open(path, 'wb+') as fd:
                fd.write(buf)
        except OSError as ex:
            self._display.error_as_warning(f"Unable to write to {hostname!r}'s file.", exception=ex)

    def result_to_tree(self, result: CallbackTaskResult) -> None:
        self.write_tree_file(result.host.get_name(), self._dump_results(result.result))

    def v2_runner_on_ok(self, result: CallbackTaskResult) -> None:
        self.result_to_tree(result)

    def v2_runner_on_failed(self, result: CallbackTaskResult, ignore_errors: bool = False) -> None:
        self.result_to_tree(result)

    def v2_runner_on_unreachable(self, result: CallbackTaskResult) -> None:
        self.result_to_tree(result)