Debian Codegraph @

ansible_collections/community/general/plugins/callback/loganalytics.py

raw
1 # Copyright (c) Ansible project
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: loganalytics
9 type: notification
10 short_description: Posts task results to Azure Log Analytics
11 author: "Cyrus Li (@zhcli) <[email protected]>"
12 description:
13 - This callback plugin posts task results in JSON formatted to an Azure Log Analytics workspace.
14 - Credits to authors of splunk callback plugin.
15 version_added: "2.4.0"
16 requirements:
17 - Whitelisting this callback plugin.
18 - An Azure log analytics work space has been established.
19 options:
20 workspace_id:
21 description: Workspace ID of the Azure log analytics workspace.
22 type: str
23 required: true
24 env:
25 - name: WORKSPACE_ID
26 ini:
27 - section: callback_loganalytics
28 key: workspace_id
29 shared_key:
30 description: Shared key to connect to Azure log analytics workspace.
31 type: str
32 required: true
33 env:
34 - name: WORKSPACE_SHARED_KEY
35 ini:
36 - section: callback_loganalytics
37 key: shared_key
38 deprecated:
39 removed_in: 14.0.0
40 why: The "HTTP Data Collector API" used by the plugin has been deprecated in Azure Monitor and replaced with the "Logs Ingestion API".
41 alternative: Please migrate to the P(community.general.loganalytics_ingestion#callback) plugin.
42 """
43
44 EXAMPLES = r"""
45 examples: |-
46 Whitelist the plugin in ansible.cfg:
47 [defaults]
48 callback_whitelist = community.general.loganalytics
49 Set the environment variable:
50 export WORKSPACE_ID=01234567-0123-0123-0123-01234567890a
51 export WORKSPACE_SHARED_KEY=dZD0kCbKl3ehZG6LHFMuhtE0yHiFCmetzFMc2u+roXIUQuatqU924SsAAAAPemhjbGlAemhjbGktTUJQAQIDBA==
52 Or configure the plugin in ansible.cfg in the callback_loganalytics block:
53 [callback_loganalytics]
54 workspace_id = 01234567-0123-0123-0123-01234567890a
55 shared_key = dZD0kCbKl3ehZG6LHFMuhtE0yHiFCmetzFMc2u+roXIUQuatqU924SsAAAAPemhjbGlAemhjbGktTUJQAQIDBA==
56 """
57
58 import base64
59 import getpass
60 import hashlib
61 import hmac
62 import json
63 import socket
64 import uuid
65 from os.path import basename
66
67 from ansible.module_utils.ansible_release import __version__ as ansible_version
68 from ansible.module_utils.urls import open_url
69 from ansible.parsing.ajson import AnsibleJSONEncoder
70 from ansible.plugins.callback import CallbackBase
71
72 from ansible_collections.community.general.plugins.module_utils._datetime import (
73 now,
74 )
75
76
77 class AzureLogAnalyticsSource:
78 def __init__(self):
79 self.ansible_check_mode = False
80 self.ansible_playbook = ""
81 self.session = str(uuid.uuid4())
82 self.host = socket.gethostname()
83 self.user = getpass.getuser()
84 self.extra_vars = ""
85
86 def __build_signature(self, date, workspace_id, shared_key, content_length):
87 # Build authorisation signature for Azure log analytics API call
88 sigs = f"POST\n{content_length}\napplication/json\nx-ms-date:{date}\n/api/logs"
89 utf8_sigs = sigs.encode("utf-8")
90 decoded_shared_key = base64.b64decode(shared_key)
91 hmac_sha256_sigs = hmac.new(decoded_shared_key, utf8_sigs, digestmod=hashlib.sha256).digest()
92 encoded_hash = base64.b64encode(hmac_sha256_sigs).decode("utf-8")
93 signature = f"SharedKey {workspace_id}:{encoded_hash}"
94 return signature
95
96 def __build_workspace_url(self, workspace_id):
97 return f"https://{workspace_id}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01"
98
99 def __rfc1123date(self):
100 return now().strftime("%a, %d %b %Y %H:%M:%S GMT")
101
102 def send_event(self, workspace_id, shared_key, state, result, runtime):
103 if result._task_fields["args"].get("_ansible_check_mode") is True:
104 self.ansible_check_mode = True
105
106 if result._task._role:
107 ansible_role = str(result._task._role)
108 else:
109 ansible_role = None
110
111 data = {}
112 data["uuid"] = result._task._uuid
113 data["session"] = self.session
114 data["status"] = state
115 data["timestamp"] = self.__rfc1123date()
116 data["host"] = self.host
117 data["user"] = self.user
118 data["runtime"] = runtime
119 data["ansible_version"] = ansible_version
120 data["ansible_check_mode"] = self.ansible_check_mode
121 data["ansible_host"] = result._host.name
122 data["ansible_playbook"] = self.ansible_playbook
123 data["ansible_role"] = ansible_role
124 data["ansible_task"] = result._task_fields
125 # Removing args since it can contain sensitive data
126 if "args" in data["ansible_task"]:
127 data["ansible_task"].pop("args")
128 data["ansible_result"] = result._result
129 if "content" in data["ansible_result"]:
130 data["ansible_result"].pop("content")
131
132 # Adding extra vars info
133 data["extra_vars"] = self.extra_vars
134
135 # Preparing the playbook logs as JSON format and send to Azure log analytics
136 jsondata = json.dumps({"event": data}, cls=AnsibleJSONEncoder, sort_keys=True)
137 content_length = len(jsondata)
138 rfc1123date = self.__rfc1123date()
139 signature = self.__build_signature(rfc1123date, workspace_id, shared_key, content_length)
140 workspace_url = self.__build_workspace_url(workspace_id)
141
142 open_url(
143 workspace_url,
144 jsondata,
145 headers={
146 "content-type": "application/json",
147 "Authorization": signature,
148 "Log-Type": "ansible_playbook",
149 "x-ms-date": rfc1123date,
150 },
151 method="POST",
152 )
153
154
155 class CallbackModule(CallbackBase):
156 CALLBACK_VERSION = 2.0
157 CALLBACK_TYPE = "notification"
158 CALLBACK_NAME = "loganalytics"
159 CALLBACK_NEEDS_WHITELIST = True
160
161 def __init__(self, display=None):
162 super().__init__(display=display)
163 self.start_datetimes = {} # Collect task start times
164 self.workspace_id = None
165 self.shared_key = None
166 self.loganalytics = AzureLogAnalyticsSource()
167
168 def _seconds_since_start(self, result):
169 return (now() - self.start_datetimes[result._task._uuid]).total_seconds()
170
171 def set_options(self, task_keys=None, var_options=None, direct=None):
172 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
173 self.workspace_id = self.get_option("workspace_id")
174 self.shared_key = self.get_option("shared_key")
175
176 def v2_playbook_on_play_start(self, play):
177 vm = play.get_variable_manager()
178 extra_vars = vm.extra_vars
179 self.loganalytics.extra_vars = extra_vars
180
181 def v2_playbook_on_start(self, playbook):
182 self.loganalytics.ansible_playbook = basename(playbook._file_name)
183
184 def v2_playbook_on_task_start(self, task, is_conditional):
185 self.start_datetimes[task._uuid] = now()
186
187 def v2_playbook_on_handler_task_start(self, task):
188 self.start_datetimes[task._uuid] = now()
189
190 def v2_runner_on_ok(self, result, **kwargs):
191 self.loganalytics.send_event(
192 self.workspace_id, self.shared_key, "OK", result, self._seconds_since_start(result)
193 )
194
195 def v2_runner_on_skipped(self, result, **kwargs):
196 self.loganalytics.send_event(
197 self.workspace_id, self.shared_key, "SKIPPED", result, self._seconds_since_start(result)
198 )
199
200 def v2_runner_on_failed(self, result, **kwargs):
201 self.loganalytics.send_event(
202 self.workspace_id, self.shared_key, "FAILED", result, self._seconds_since_start(result)
203 )
204
205 def runner_on_async_failed(self, result, **kwargs):
206 self.loganalytics.send_event(
207 self.workspace_id, self.shared_key, "FAILED", result, self._seconds_since_start(result)
208 )
209
210 def v2_runner_on_unreachable(self, result, **kwargs):
211 self.loganalytics.send_event(
212 self.workspace_id, self.shared_key, "UNREACHABLE", result, self._seconds_since_start(result)
213 )