Debian Codegraph @

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

raw
1 #!/usr/bin/env python
2 # Copyright (c) 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 = """
9 name: loganalytics_ingestion
10 type: notification
11 short_description: Posts task results to an Azure Log Analytics workspace using the new Logs Ingestion API
12 author:
13 - Wade Cline (@wtcline-intc) <[email protected]>
14 - Sriramoju Vishal Bharath (@vsh47) <[email protected]>
15 - Cyrus Li (@zhcli) <[email protected]>
16 description:
17 - This callback plugin will post task results in JSON format to an Azure Log Analytics workspace using the new Logs Ingestion API.
18 version_added: "12.4.0"
19 requirements:
20 - The callback plugin has been enabled.
21 - An Azure Log Analytics workspace has been established.
22 - A Data Collection Rule (DCR) and custom table are created.
23 options:
24 dce_url:
25 description: URL of the Data Collection Endpoint (DCE) for Azure Logs Ingestion API.
26 type: str
27 required: true
28 env:
29 - name: ANSIBLE_LOGANALYTICS_DCE_URL
30 ini:
31 - section: callback_loganalytics
32 key: dce_url
33 dcr_id:
34 description: Data Collection Rule (DCR) ID for the Azure Log Ingestion API.
35 type: str
36 required: true
37 env:
38 - name: ANSIBLE_LOGANALYTICS_DCR_ID
39 ini:
40 - section: callback_loganalytics
41 key: dcr_id
42 disable_attempts:
43 description:
44 - When O(disable_on_failure=true), number of plugin failures that must occur before the plugin is disabled.
45 - This helps prevent outright plugin failure from a single, transient network issue.
46 type: int
47 default: 3
48 env:
49 - name: ANSIBLE_LOGANALYTICS_DISABLE_ATTEMPTS
50 ini:
51 - section: callback_loganalytics
52 key: disable_attempts
53 disable_on_failure:
54 description: Stop trying to send data on plugin failure.
55 type: bool
56 default: true
57 env:
58 - name: ANSIBLE_LOGANALYTICS_DISABLE_ON_FAILURE
59 ini:
60 - section: callback_loganalytics
61 key: disable_on_failure
62 client_id:
63 description: Client ID of the Azure App registration for OAuth2 authentication ("Modern Authentication").
64 type: str
65 required: true
66 env:
67 - name: ANSIBLE_LOGANALYTICS_CLIENT_ID
68 ini:
69 - section: callback_loganalytics
70 key: client_id
71 client_secret:
72 description: Client Secret of the Azure App registration.
73 type: str
74 required: true
75 env:
76 - name: ANSIBLE_LOGANALYTICS_CLIENT_SECRET
77 ini:
78 - section: callback_loganalytics
79 key: client_secret
80 include_content:
81 description: Send the content to the Azure Log Analytics workspace.
82 type: bool
83 default: false
84 env:
85 - name: ANSIBLE_LOGANALYTICS_INCLUDE_CONTENT
86 ini:
87 - section: callback_loganalytics
88 key: include_content
89 include_task_args:
90 description: Send the task args to the Azure Log Analytics workspace.
91 type: bool
92 default: false
93 env:
94 - name: ANSIBLE_LOGANALYTICS_INCLUDE_TASK_ARGS
95 ini:
96 - section: callback_loganalytics
97 key: include_task_args
98 stream_name:
99 description: The name of the stream used to send the logs to the Azure Log Analytics workspace.
100 type: str
101 required: true
102 env:
103 - name: ANSIBLE_LOGANALYTICS_STREAM_NAME
104 ini:
105 - section: callback_loganalytics
106 key: stream_name
107 tenant_id:
108 description: Tenant ID for the Azure Active Directory.
109 type: str
110 required: true
111 env:
112 - name: ANSIBLE_LOGANALYTICS_TENANT_ID
113 ini:
114 - section: callback_loganalytics
115 key: tenant_id
116 timeout:
117 description: Timeout for the HTTP requests to the Azure Log Analytics API.
118 type: int
119 default: 2
120 env:
121 - name: ANSIBLE_LOGANALYTICS_TIMEOUT
122 ini:
123 - section: callback_loganalytics
124 key: timeout
125 seealso:
126 - name: Logs Ingestion API
127 description: Overview of Logs Ingestion API in Azure Monitor
128 link: https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview
129 notes:
130 - Triple verbosity logging (C(-vvv)) can be used to generate JSON sample data for creating the table schema in Azure Log Analytics.
131 Search for the string C(Event Data:) in the output in order to locate the data sample.
132 """
133
134 EXAMPLES = """
135 examples: |
136 Enable the plugin in ansible.cfg:
137 [defaults]
138 callback_enabled = community.general.loganalytics_ingestion
139 Set the environment variables:
140 export ANSIBLE_LOGANALYTICS_DCE_URL=https://my-dce.ingest.monitor.azure.com
141 export ANSIBLE_LOGANALYTICS_DCR_ID=dcr-xxxxxx
142 export ANSIBLE_LOGANALYTICS_CLIENT_ID=xxxxxxxx
143 export ANSIBLE_LOGANALYTICS_CLIENT_SECRET=xxxxxxxx
144 export ANSIBLE_LOGANALYTICS_TENANT_ID=xxxxxxxx
145 export ANSIBLE_LOGANALYTICS_STREAM_NAME=Custom-MyTable
146 """
147
148 import getpass
149 import json
150 import socket
151 import uuid
152 from datetime import datetime, timedelta, timezone
153 from os.path import basename
154 from urllib.parse import urlencode
155
156 from ansible.module_utils.urls import open_url
157 from ansible.plugins.callback import CallbackBase
158 from ansible.utils.display import Display
159
160 display = Display()
161
162
163 class AzureLogAnalyticsIngestionSource:
164 def __init__(
165 self,
166 dce_url,
167 dcr_id,
168 disable_attempts,
169 disable_on_failure,
170 client_id,
171 client_secret,
172 tenant_id,
173 stream_name,
174 include_task_args,
175 include_content,
176 timeout,
177 fqcn,
178 ):
179 self.dce_url = dce_url
180 self.dcr_id = dcr_id
181 self.disabled = False
182 self.disable_attempts = disable_attempts
183 self.disable_on_failure = disable_on_failure
184 self.client_id = client_id
185 self.client_secret = client_secret
186 self.failures = 0
187 self.tenant_id = tenant_id
188 self.stream_name = stream_name
189 self.include_task_args = include_task_args
190 self.include_content = include_content
191 self.token_expiration_time = None
192 self.session = str(uuid.uuid4())
193 self.host = socket.gethostname()
194 self.user = getpass.getuser()
195 self.timeout = timeout
196 self.fqcn = fqcn
197
198 self.bearer_token = self.get_bearer_token()
199
200 # OAuth2 authentication method to get a Bearer token
201 # This replaces the shared_key authentication mechanism
202 def get_bearer_token(self):
203 url = f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token"
204 headers = {"Content-Type": "application/x-www-form-urlencoded"}
205 data = urlencode(
206 {
207 "grant_type": "client_credentials",
208 "client_id": self.client_id,
209 "client_secret": self.client_secret,
210 # The scope value comes from https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview#headers
211 # and https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-default-scope
212 "scope": "https://monitor.azure.com/.default",
213 }
214 )
215 response = open_url(url, data=data, force=True, headers=headers, method="POST", timeout=self.timeout)
216 j = json.loads(response.read().decode("utf-8"))
217 self.token_expiration_time = datetime.now() + timedelta(seconds=j.get("expires_in"))
218 return j.get("access_token")
219
220 def is_token_valid(self):
221 return datetime.now() + timedelta(seconds=10) < self.token_expiration_time
222
223 # Method to send event data to the Azure Logs Ingestion API
224 # This replaces the legacy API call and now uses the Logs Ingestion API endpoint
225 def send_event(self, event_data):
226 if not self.is_token_valid():
227 self.bearer_token = self.get_bearer_token()
228 ingestion_url = (
229 f"{self.dce_url}/dataCollectionRules/{self.dcr_id}/streams/{self.stream_name}?api-version=2023-01-01"
230 )
231 headers = {"Authorization": f"Bearer {self.bearer_token}", "Content-Type": "application/json"}
232 open_url(ingestion_url, data=json.dumps(event_data), headers=headers, method="POST", timeout=self.timeout)
233
234 def _rfc1123date(self):
235 return datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT")
236
237 # This method wraps the private method with the appropriate error handling.
238 def send_to_loganalytics(self, playbook_name, result, state):
239 if self.disabled:
240 return
241 try:
242 self._send_to_loganalytics(playbook_name, result, state)
243 except Exception as e:
244 display.warning(f"{self.fqcn} callback plugin failure: {e}.")
245 if self.disable_on_failure:
246 self.failures += 1
247 if self.failures >= self.disable_attempts:
248 display.warning(
249 f"{self.fqcn} callback plugin failures exceed maximum of '{self.disable_attempts}'! Disabling plugin!"
250 )
251 self.disabled = True
252 else:
253 display.v(f"{self.fqcn} callback plugin failure {self.failures}/{self.disable_attempts}")
254
255 def _send_to_loganalytics(self, playbook_name, result, state):
256 ansible_role = str(result._task._role) if result._task._role else None
257
258 # Include/Exclude task args
259 if not self.include_task_args:
260 result._task_fields.pop("args", None)
261
262 # Include/Exclude content
263 if not self.include_content:
264 result._result.pop("content", None)
265
266 # Build the event data
267 event_data = [
268 {
269 "TimeGenerated": self._rfc1123date(),
270 "Host": result._host.name,
271 "User": self.user,
272 "Playbook": playbook_name,
273 "Role": ansible_role,
274 "TaskName": result._task.get_name(),
275 "Task": result._task_fields,
276 "Action": result._task_fields["action"],
277 "State": state,
278 "Result": result._result,
279 "Session": self.session,
280 }
281 ]
282
283 # The data displayed here can be used as a sample file in order to create the table's schema.
284 display.vvv(f"Event Data: {json.dumps(event_data)}")
285
286 self.send_event(event_data)
287
288
289 class CallbackModule(CallbackBase):
290 CALLBACK_VERSION = 2.0
291 CALLBACK_TYPE = "notification"
292 CALLBACK_NAME = "loganalytics_ingestion"
293 CALLBACK_NEEDS_ENABLED = True
294
295 def __init__(self, display=None):
296 super().__init__(display=display)
297 self.start_datetimes = {}
298 self.playbook_name = None
299 self.azure_loganalytics = None
300 self.fqcn = f"community.general.{self.CALLBACK_NAME}"
301
302 def set_options(self, task_keys=None, var_options=None, direct=None):
303 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
304
305 # Set options for the new Azure Logs Ingestion API configuration
306 self.client_id = self.get_option("client_id")
307 self.client_secret = self.get_option("client_secret")
308 self.dce_url = self.get_option("dce_url")
309 self.dcr_id = self.get_option("dcr_id")
310 self.disable_attempts = self.get_option("disable_attempts")
311 self.disable_on_failure = self.get_option("disable_on_failure")
312 self.include_content = self.get_option("include_content")
313 self.include_task_args = self.get_option("include_task_args")
314 self.stream_name = self.get_option("stream_name")
315 self.tenant_id = self.get_option("tenant_id")
316 self.timeout = self.get_option("timeout")
317
318 # Initialize the AzureLogAnalyticsIngestionSource with the new settings
319 self.azure_loganalytics = AzureLogAnalyticsIngestionSource(
320 self.dce_url,
321 self.dcr_id,
322 self.disable_attempts,
323 self.disable_on_failure,
324 self.client_id,
325 self.client_secret,
326 self.tenant_id,
327 self.stream_name,
328 self.include_task_args,
329 self.include_content,
330 self.timeout,
331 self.fqcn,
332 )
333
334 def v2_playbook_on_start(self, playbook):
335 self.playbook_name = basename(playbook._file_name)
336
337 # Build event data and send it to the Logs Ingestion API
338 def v2_runner_on_failed(self, result, **kwargs):
339 self.azure_loganalytics.send_to_loganalytics(self.playbook_name, result, "FAILED")
340
341 def v2_runner_on_ok(self, result, **kwargs):
342 self.azure_loganalytics.send_to_loganalytics(self.playbook_name, result, "OK")