Debian Codegraph @

ansible_collections/splunk/es/plugins/action/splunk_notes.py

raw
1 #
2 # Copyright 2026 Red Hat Inc.
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """
21 The action module for splunk_notes
22 """
23
24 from typing import Any, Optional
25
26 from ansible.errors import AnsibleActionFail
27 from ansible.module_utils.connection import Connection
28 from ansible.module_utils.six.moves.urllib.parse import quote
29 from ansible.plugins.action import ActionBase
30 from ansible.utils.display import Display
31
32 from ansible_collections.splunk.es.plugins.module_utils.finding import extract_notable_time
33 from ansible_collections.splunk.es.plugins.module_utils.notes import (
34 TARGET_FINDING,
35 TARGET_RESPONSE_PLAN_TASK,
36 build_note_api_path,
37 build_notes_api_path,
38 build_task_note_api_path,
39 build_task_notes_api_path,
40 map_note_from_api,
41 map_note_to_api,
42 validate_target_params,
43 )
44 from ansible_collections.splunk.es.plugins.module_utils.splunk import (
45 SplunkRequest,
46 check_argspec,
47 )
48 from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import (
49 DEFAULT_API_APP,
50 DEFAULT_API_NAMESPACE,
51 DEFAULT_API_USER,
52 get_api_config_from_args,
53 )
54 from ansible_collections.splunk.es.plugins.modules.splunk_notes import DOCUMENTATION
55
56
57 # Initialize display for debug output
58 display = Display()
59
60
61 class ActionModule(ActionBase):
62 """Action module for managing Splunk ES notes."""
63
64 def __init__(self, *args: Any, **kwargs: Any) -> None:
65 super().__init__(*args, **kwargs)
66 self._result: dict[str, Any] = {}
67 self.module_name = "note"
68 self.api_namespace = DEFAULT_API_NAMESPACE
69 self.api_user = DEFAULT_API_USER
70 self.api_app = DEFAULT_API_APP
71
72 def fail_json(self, msg: str) -> None:
73 """Raise an AnsibleActionFail with a cleaned up message.
74
75 Args:
76 msg: The message for the failure.
77
78 Raises:
79 AnsibleActionFail: Always raised with the provided message.
80 """
81 msg = msg.replace("(basic.py)", self._task.action)
82 raise AnsibleActionFail(msg)
83
84 def _configure_api(self) -> None:
85 """Configure API path components from task arguments."""
86 self.api_namespace, self.api_user, self.api_app = get_api_config_from_args(
87 self._task.args,
88 )
89
90 def _validate_state_params(self, state: str, note_id: Optional[str]) -> Optional[str]:
91 """Validate parameters based on state.
92
93 Args:
94 state: The desired state (present or absent).
95 note_id: The note ID (if provided).
96
97 Returns:
98 Error message if validation fails, None if valid.
99 """
100 if state == "absent":
101 if not note_id:
102 return "Missing required parameter 'note_id' for state 'absent'"
103 elif state == "present":
104 content = self._task.args.get("content")
105 if not content:
106 return "Missing required parameter 'content' for state 'present'"
107
108 return None
109
110 def _build_note_params(self) -> dict[str, Any]:
111 """Build note dictionary from task arguments.
112
113 Returns:
114 Dictionary containing note parameters from task args.
115 """
116 note: dict[str, Any] = {}
117
118 content = self._task.args.get("content")
119 if content is not None:
120 note["content"] = content
121
122 return note
123
124 def _build_notes_path(self, target_type: str) -> str:
125 """Build the notes API path based on target type.
126
127 Args:
128 target_type: The target type.
129
130 Returns:
131 The API path for notes.
132 """
133 if target_type == TARGET_RESPONSE_PLAN_TASK:
134 return build_task_notes_api_path(
135 investigation_id=self._task.args.get("investigation_ref_id"),
136 response_plan_id=self._task.args.get("response_plan_id"),
137 phase_id=self._task.args.get("phase_id"),
138 task_id=self._task.args.get("task_id"),
139 namespace=self.api_namespace,
140 user=self.api_user,
141 app=self.api_app,
142 )
143
144 # For finding or investigation
145 if target_type == TARGET_FINDING:
146 investigation_id = quote(self._task.args.get("finding_ref_id"), safe="")
147 else:
148 investigation_id = self._task.args.get("investigation_ref_id")
149
150 return build_notes_api_path(
151 investigation_id=investigation_id,
152 namespace=self.api_namespace,
153 user=self.api_user,
154 app=self.api_app,
155 )
156
157 def _build_note_path(self, target_type: str, note_id: str) -> str:
158 """Build the API path for a specific note.
159
160 Args:
161 target_type: The target type.
162 note_id: The note ID.
163
164 Returns:
165 The API path for the specific note.
166 """
167 if target_type == TARGET_RESPONSE_PLAN_TASK:
168 return build_task_note_api_path(
169 investigation_id=self._task.args.get("investigation_ref_id"),
170 response_plan_id=self._task.args.get("response_plan_id"),
171 phase_id=self._task.args.get("phase_id"),
172 task_id=self._task.args.get("task_id"),
173 note_id=note_id,
174 namespace=self.api_namespace,
175 user=self.api_user,
176 app=self.api_app,
177 )
178
179 # For finding or investigation
180 if target_type == TARGET_FINDING:
181 investigation_id = quote(self._task.args.get("finding_ref_id"), safe="")
182 else:
183 investigation_id = self._task.args.get("investigation_ref_id")
184
185 return build_note_api_path(
186 investigation_id=investigation_id,
187 note_id=note_id,
188 namespace=self.api_namespace,
189 user=self.api_user,
190 app=self.api_app,
191 )
192
193 def _get_query_params(self, target_type: str) -> dict[str, str]:
194 """Get query parameters for API requests.
195
196 For findings, extracts notable_time from finding_ref_id.
197
198 Args:
199 target_type: The target type.
200
201 Returns:
202 Query parameters dict (empty if no params needed).
203 """
204 if target_type == TARGET_FINDING:
205 finding_ref_id = self._task.args.get("finding_ref_id")
206 notable_time = extract_notable_time(finding_ref_id)
207 if notable_time:
208 display.vvv(f"splunk_notes: using notable_time={notable_time} from finding_ref_id")
209 return {"notable_time": notable_time}
210 return {}
211
212 def _get_all_notes(
213 self,
214 conn_request: SplunkRequest,
215 target_type: str,
216 ) -> list[dict[str, Any]]:
217 """Get all notes for a target.
218
219 Args:
220 conn_request: The SplunkRequest instance.
221 target_type: The target type.
222
223 Returns:
224 List of notes, or empty list if none found.
225 """
226 api_path = self._build_notes_path(target_type)
227 query_params = self._get_query_params(target_type)
228 # Request maximum notes (100) sorted by newest first
229 query_params["limit"] = 100
230 query_params["sort"] = "create_time:-1"
231
232 display.vvv(f"splunk_notes: GET {api_path}")
233 response = conn_request.get_by_path(api_path, query_params=query_params)
234
235 display.vvv(f"splunk_notes: list notes raw response: {response}")
236
237 if not response:
238 display.vv("splunk_notes: no notes found (empty response)")
239 return []
240
241 # Extract notes from response
242 notes = response.get("items", [])
243
244 if notes:
245 display.vvv(f"splunk_notes: found {len(notes)} notes")
246 else:
247 display.vv("splunk_notes: no notes found in response")
248
249 return notes
250
251 def _get_note_by_id(
252 self,
253 conn_request: SplunkRequest,
254 target_type: str,
255 note_id: str,
256 ) -> dict[str, Any]:
257 """Get an existing note by its ID.
258
259 Fetches all notes for the target and filters by note_id,
260 API doesn't support GET for a single note.
261
262 Args:
263 conn_request: The SplunkRequest instance.
264 target_type: The target type.
265 note_id: The note ID.
266
267 Returns:
268 The existing note if found, empty dict otherwise.
269 """
270 display.vv(f"splunk_notes: getting note by id: {note_id}")
271
272 # Fetch all notes and filter by ID
273 all_notes = self._get_all_notes(conn_request, target_type)
274
275 for note in all_notes:
276 if note.get("id") == note_id:
277 display.vvv(f"splunk_notes: found note: {note}")
278 return map_note_from_api(note)
279
280 display.vv(f"splunk_notes: no note found with id: {note_id}")
281 return {}
282
283 def _create_note(
284 self,
285 conn_request: SplunkRequest,
286 target_type: str,
287 note: dict[str, Any],
288 ) -> dict[str, Any]:
289 """Create a new note.
290
291 Args:
292 conn_request: The SplunkRequest instance.
293 target_type: The target type.
294 note: The note parameters.
295
296 Returns:
297 The created note from API response.
298 """
299 api_path = self._build_notes_path(target_type)
300 query_params = self._get_query_params(target_type)
301 payload = map_note_to_api(note)
302
303 display.vvv(f"splunk_notes: POST {api_path}")
304 display.vvv(f"splunk_notes: payload: {payload}")
305
306 response = conn_request.create_update(
307 api_path,
308 data=payload,
309 query_params=query_params,
310 json_payload=True,
311 )
312
313 if response:
314 display.vvv(f"splunk_notes: create response: {response}")
315 return map_note_from_api(response)
316
317 return {}
318
319 def _update_note(
320 self,
321 conn_request: SplunkRequest,
322 target_type: str,
323 note_id: str,
324 note: dict[str, Any],
325 ) -> dict[str, Any]:
326 """Update an existing note.
327
328 Args:
329 conn_request: The SplunkRequest instance.
330 target_type: The target type.
331 note_id: The note ID.
332 note: The note parameters.
333
334 Returns:
335 The updated note from API response.
336 """
337 api_path = self._build_note_path(target_type, note_id)
338 query_params = self._get_query_params(target_type)
339 payload = map_note_to_api(note)
340
341 display.vvv(f"splunk_notes: POST {api_path}")
342 display.vvv(f"splunk_notes: payload: {payload}")
343
344 response = conn_request.create_update(
345 api_path,
346 data=payload,
347 query_params=query_params,
348 json_payload=True,
349 )
350
351 if response:
352 display.vvv(f"splunk_notes: update response: {response}")
353 return map_note_from_api(response)
354
355 # Return expected state if no response
356 result = note.copy()
357 result["note_id"] = note_id
358 return result
359
360 def _delete_note(
361 self,
362 conn_request: SplunkRequest,
363 target_type: str,
364 note_id: str,
365 ) -> None:
366 """Delete a note.
367
368 Args:
369 conn_request: The SplunkRequest instance.
370 target_type: The target type.
371 note_id: The note ID.
372 """
373 api_path = self._build_note_path(target_type, note_id)
374
375 display.vvv(f"splunk_notes: DELETE {api_path}")
376 conn_request.delete_by_path(api_path)
377
378 def _compare_notes(
379 self,
380 existing: dict[str, Any],
381 desired: dict[str, Any],
382 ) -> bool:
383 """Compare existing and desired note states.
384
385 Args:
386 existing: The existing note state.
387 desired: The desired note state.
388
389 Returns:
390 True if notes are different, False if same.
391 """
392 # Compare content
393 return existing.get("content") != desired.get("content")
394
395 def _handle_present_create(
396 self,
397 conn_request: SplunkRequest,
398 target_type: str,
399 note: dict[str, Any],
400 ) -> None:
401 """Handle creating a new note.
402
403 Args:
404 conn_request: The SplunkRequest instance.
405 target_type: The target type.
406 note: The note parameters.
407 """
408 display.v("splunk_notes: creating new note")
409
410 if self._task.check_mode:
411 display.v("splunk_notes: check mode - would create note")
412 self._result[self.module_name] = {"before": None, "after": note}
413 self._result["changed"] = True
414 self._result["msg"] = "Check mode: would create note"
415 return
416
417 after = self._create_note(conn_request, target_type, note)
418
419 self._result[self.module_name] = {"before": None, "after": after}
420 self._result["changed"] = True
421 self._result["msg"] = "Note created successfully"
422 display.v("splunk_notes: note created successfully")
423
424 def _handle_present_update(
425 self,
426 conn_request: SplunkRequest,
427 target_type: str,
428 note_id: str,
429 note: dict[str, Any],
430 ) -> None:
431 """Handle updating an existing note.
432
433 Args:
434 conn_request: The SplunkRequest instance.
435 target_type: The target type.
436 note_id: The note ID.
437 note: The note parameters.
438 """
439 display.v(f"splunk_notes: updating note with id: {note_id}")
440
441 # Get existing note
442 existing = self._get_note_by_id(conn_request, target_type, note_id)
443
444 if not existing:
445 self._result["failed"] = True
446 self._result["msg"] = f"Note with id '{note_id}' not found"
447 return
448
449 # Check if update is needed
450 if not self._compare_notes(existing, note):
451 display.v("splunk_notes: no changes needed")
452 self._result[self.module_name] = {"before": existing, "after": existing}
453 self._result["changed"] = False
454 self._result["msg"] = "No changes required"
455 return
456
457 display.vv("splunk_notes: changes detected, updating note")
458
459 if self._task.check_mode:
460 display.v("splunk_notes: check mode - would update note")
461 after = existing.copy()
462 after.update(note)
463 self._result[self.module_name] = {"before": existing, "after": after}
464 self._result["changed"] = True
465 self._result["msg"] = "Check mode: would update note"
466 return
467
468 after = self._update_note(conn_request, target_type, note_id, note)
469
470 # Compare before and after to determine if API actually made changes
471 actually_changed = self._compare_notes(existing, after)
472
473 self._result[self.module_name] = {"before": existing, "after": after}
474 self._result["changed"] = actually_changed
475 if actually_changed:
476 self._result["msg"] = "Note updated successfully"
477 display.v("splunk_notes: note updated successfully")
478 else:
479 self._result["msg"] = "No changes required"
480 display.v("splunk_notes: no actual changes made by API")
481
482 def _handle_present(
483 self,
484 conn_request: SplunkRequest,
485 target_type: str,
486 note_id: Optional[str],
487 note: dict[str, Any],
488 ) -> None:
489 """Handle state=present operation.
490
491 Args:
492 conn_request: The SplunkRequest instance.
493 target_type: The target type.
494 note_id: The note ID (if updating).
495 note: The note parameters.
496 """
497 if note_id:
498 self._handle_present_update(conn_request, target_type, note_id, note)
499 else:
500 self._handle_present_create(conn_request, target_type, note)
501
502 def _handle_absent(
503 self,
504 conn_request: SplunkRequest,
505 target_type: str,
506 note_id: str,
507 ) -> None:
508 """Handle state=absent operation.
509
510 Args:
511 conn_request: The SplunkRequest instance.
512 target_type: The target type.
513 note_id: The note ID.
514 """
515 display.v(f"splunk_notes: deleting note with id: {note_id}")
516
517 # Get existing note to verify it exists
518 existing = self._get_note_by_id(conn_request, target_type, note_id)
519
520 if not existing:
521 display.v("splunk_notes: note not found, already absent")
522 self._result[self.module_name] = {"before": None, "after": None}
523 self._result["changed"] = False
524 self._result["msg"] = "Note not found, already absent"
525 return
526
527 if self._task.check_mode:
528 display.v("splunk_notes: check mode - would delete note")
529 self._result[self.module_name] = {"before": existing, "after": None}
530 self._result["changed"] = True
531 self._result["msg"] = "Check mode: would delete note"
532 return
533
534 self._delete_note(conn_request, target_type, note_id)
535
536 self._result[self.module_name] = {"before": existing, "after": None}
537 self._result["changed"] = True
538 self._result["msg"] = "Note deleted successfully"
539 display.v("splunk_notes: note deleted successfully")
540
541 def run(self, tmp=None, task_vars=None):
542 """Execute the action module."""
543 self._supports_check_mode = True
544 self._result = super().run(tmp, task_vars)
545
546 display.v("splunk_notes: starting module execution")
547
548 # Validate arguments
549 if not check_argspec(self, self._result, DOCUMENTATION):
550 display.v(f"splunk_notes: argument validation failed: {self._result.get('msg')}")
551 return self._result
552
553 # Initialize result structure
554 self._result[self.module_name] = {}
555 self._result["changed"] = False
556
557 self._configure_api()
558
559 # Extract parameters
560 target_type = self._task.args.get("target_type")
561 state = self._task.args.get("state", "present")
562 note_id = self._task.args.get("note_id")
563
564 display.vv(f"splunk_notes: target_type: {target_type}")
565 display.vv(f"splunk_notes: state: {state}")
566 display.vv(f"splunk_notes: note_id: {note_id}")
567
568 # Validate target-specific parameters
569 error = validate_target_params(target_type, self._task.args)
570 if error:
571 self._result["failed"] = True
572 self._result["msg"] = error
573 display.v(f"splunk_notes: {error}")
574 return self._result
575
576 # Validate state-specific parameters
577 error = self._validate_state_params(state, note_id)
578 if error:
579 self._result["failed"] = True
580 self._result["msg"] = error
581 display.v(f"splunk_notes: {error}")
582 return self._result
583
584 # Build note parameters
585 note = self._build_note_params()
586 display.vvv(f"splunk_notes: note parameters: {note}")
587
588 # Setup connection
589 conn = Connection(self._connection.socket_path)
590 conn_request = SplunkRequest(
591 action_module=self,
592 connection=conn,
593 not_rest_data_keys=[
594 "target_type",
595 "state",
596 "note_id",
597 "finding_ref_id",
598 "investigation_ref_id",
599 "response_plan_id",
600 "phase_id",
601 "task_id",
602 "api_namespace",
603 "api_user",
604 "api_app",
605 ],
606 )
607
608 # Route based on state
609 if state == "absent":
610 self._handle_absent(conn_request, target_type, note_id)
611 else:
612 self._handle_present(conn_request, target_type, note_id, note)
613
614 display.v(f"splunk_notes: module completed with changed={self._result['changed']}")
615 return self._result