Debian Codegraph @

ansible_collections/splunk/es/plugins/action/splunk_response_plan.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_response_plan
22 """
23
24 import uuid
25
26 from typing import Any, Optional
27
28 from ansible.errors import AnsibleActionFail
29 from ansible.module_utils.connection import Connection
30 from ansible.module_utils.six.moves.urllib.parse import unquote
31 from ansible.plugins.action import ActionBase
32 from ansible.utils.display import Display
33
34 from ansible_collections.splunk.es.plugins.module_utils.splunk import (
35 SplunkRequest,
36 check_argspec,
37 )
38 from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import (
39 DEFAULT_API_APP,
40 DEFAULT_API_NAMESPACE,
41 DEFAULT_API_USER,
42 )
43 from ansible_collections.splunk.es.plugins.modules.splunk_response_plan import DOCUMENTATION
44
45
46 # Initialize display for debug output
47 display = Display()
48
49
50 def _generate_uuid() -> str:
51 """Generate a new UUID string.
52
53 Returns:
54 A new UUID4 string.
55 """
56 return str(uuid.uuid4())
57
58
59 def _build_response_plan_api_path(
60 namespace: str = DEFAULT_API_NAMESPACE,
61 user: str = DEFAULT_API_USER,
62 app: str = DEFAULT_API_APP,
63 ) -> str:
64 """Build the response plans API path from components.
65
66 Args:
67 namespace: The namespace portion of the path. Defaults to 'servicesNS'.
68 user: The user portion of the path. Defaults to 'nobody'.
69 app: The app portion of the path. Defaults to 'missioncontrol'.
70
71 Returns:
72 The complete response plans API path.
73 """
74 return f"{namespace}/{user}/{app}/v1/responsetemplates"
75
76
77 def _build_response_plan_update_path(
78 ref_id: str,
79 namespace: str = DEFAULT_API_NAMESPACE,
80 user: str = DEFAULT_API_USER,
81 app: str = DEFAULT_API_APP,
82 ) -> str:
83 """Build the response plan update/delete API path.
84
85 Args:
86 ref_id: The response plan reference ID.
87 namespace: The namespace portion of the path. Defaults to 'servicesNS'.
88 user: The user portion of the path. Defaults to 'nobody'.
89 app: The app portion of the path. Defaults to 'missioncontrol'.
90
91 Returns:
92 The response plan update API path with ref_id.
93 """
94 return f"{_build_response_plan_api_path(namespace, user, app)}/{ref_id}"
95
96
97 def _find_task_id_by_name(
98 existing_tasks: list[dict[str, Any]],
99 task_name: str,
100 ) -> Optional[str]:
101 """Find existing task ID by name within a phase.
102
103 Args:
104 existing_tasks: List of existing task dictionaries from a phase.
105 task_name: The task name to search for.
106
107 Returns:
108 The task ID if found, None otherwise.
109 """
110 for task in existing_tasks:
111 if task.get("name") == task_name:
112 return task.get("id")
113 return None
114
115
116 def _build_search_payload(search: dict[str, Any]) -> dict[str, Any]:
117 """Build search entry payload from user input.
118
119 Args:
120 search: User-provided search dictionary with name, description, spl.
121
122 Returns:
123 Search payload dictionary for API.
124 """
125 return {
126 "name": search.get("name", ""),
127 "description": search.get("description", ""),
128 "spl": search.get("spl", ""),
129 }
130
131
132 def _build_task_payload(
133 task: dict[str, Any],
134 order: int,
135 existing_id: Optional[str] = None,
136 ) -> dict[str, Any]:
137 """Build single task payload for API.
138
139 Args:
140 task: User-provided task dictionary.
141 order: The order/position of the task within the phase.
142 existing_id: Existing task ID if updating, None for new task.
143
144 Returns:
145 Task payload dictionary for API.
146 """
147 is_new_task = existing_id is None
148 task_id = existing_id if existing_id else _generate_uuid()
149
150 # Build searches list
151 searches = []
152 for search in task.get("searches", []) or []:
153 searches.append(_build_search_payload(search))
154
155 return {
156 "task_id": "",
157 "phase_id": "",
158 "id": task_id,
159 "name": task.get("name", ""),
160 "description": task.get("description", ""),
161 "sla": None,
162 "sla_type": "minutes",
163 "order": order,
164 "status": "Pending",
165 "is_note_required": task.get("is_note_required", False),
166 "owner": task.get("owner", "unassigned"),
167 "isNewTask": is_new_task,
168 "files": [],
169 "notes": [],
170 "suggestions": {
171 "actions": [],
172 "playbooks": [],
173 "searches": searches,
174 },
175 }
176
177
178 def _build_phase_payload(
179 phase: dict[str, Any],
180 order: int,
181 existing_phase: Optional[dict[str, Any]] = None,
182 ) -> dict[str, Any]:
183 """Build single phase payload for API.
184
185 Args:
186 phase: User-provided phase dictionary.
187 order: The order/position of the phase.
188 existing_phase: Existing phase data if updating, None for new phase.
189
190 Returns:
191 Phase payload dictionary for API.
192 """
193 existing_id = existing_phase.get("id") if existing_phase else None
194 phase_id = existing_id if existing_id else _generate_uuid()
195
196 # Get existing tasks for ID matching
197 existing_tasks = existing_phase.get("tasks", []) if existing_phase else []
198
199 # Build tasks list
200 tasks = []
201 for task_order, task in enumerate(phase.get("tasks", []) or [], start=1):
202 existing_task_id = _find_task_id_by_name(existing_tasks, task.get("name", ""))
203 tasks.append(_build_task_payload(task, task_order, existing_task_id))
204
205 return {
206 "template_id": "",
207 "id": phase_id,
208 "name": phase.get("name", ""),
209 "sla": None,
210 "sla_type": "minutes",
211 "create_time": "",
212 "order": order,
213 "tasks": tasks,
214 }
215
216
217 def _map_response_plan_to_api(
218 response_plan: dict[str, Any],
219 existing_response_plan: Optional[dict[str, Any]] = None,
220 ) -> dict[str, Any]:
221 """Convert module params to API payload format.
222
223 Handles both creation (no existing data) and update (with ID matching).
224
225 Args:
226 response_plan: User-provided response plan parameters.
227 existing_response_plan: Existing response plan from API if updating.
228
229 Returns:
230 Dictionary formatted for the Splunk response templates API.
231 """
232 # Get existing phases for ID matching
233 existing_phases = existing_response_plan.get("phases", []) if existing_response_plan else []
234
235 # Build phases list with ID matching
236 phases = []
237 for phase_order, phase in enumerate(response_plan.get("phases", []) or [], start=1):
238 # Find existing phase by name
239 existing_phase = None
240 for ep in existing_phases:
241 if ep.get("name") == phase.get("name"):
242 existing_phase = ep
243 break
244 phases.append(_build_phase_payload(phase, phase_order, existing_phase))
245
246 payload = {
247 "name": response_plan.get("name", ""),
248 "description": response_plan.get("description", ""),
249 "template_status": response_plan.get("template_status", "draft"),
250 "incident_types": [],
251 "phases": phases,
252 }
253
254 # Add response plan ID if updating
255 if existing_response_plan and existing_response_plan.get("id"):
256 payload["id"] = existing_response_plan["id"]
257
258 return payload
259
260
261 def _map_task_from_api(task: dict[str, Any]) -> dict[str, Any]:
262 """Convert single task from API format to module format.
263
264 Args:
265 task: Task dictionary from API response.
266
267 Returns:
268 Task in module format.
269 """
270 # Extract searches from suggestions
271 searches = []
272 suggestions = task.get("suggestions", {}) or {}
273 for search in suggestions.get("searches", []) or []:
274 searches.append(
275 {
276 "name": unquote(search.get("name", "")),
277 "description": unquote(search.get("description", "")),
278 "spl": unquote(search.get("spl", "")),
279 },
280 )
281
282 return {
283 "name": unquote(task.get("name", "")),
284 "description": unquote(task.get("description", "")),
285 "is_note_required": task.get("is_note_required", False),
286 "owner": task.get("owner", "unassigned"),
287 "searches": searches,
288 }
289
290
291 def _map_phase_from_api(phase: dict[str, Any]) -> dict[str, Any]:
292 """Convert single phase from API format to module format.
293
294 Args:
295 phase: Phase dictionary from API response.
296
297 Returns:
298 Phase in module format.
299 """
300 tasks = []
301 for task in phase.get("tasks", []) or []:
302 tasks.append(_map_task_from_api(task))
303
304 return {
305 "name": unquote(phase.get("name", "")),
306 "tasks": tasks,
307 }
308
309
310 def _map_response_plan_from_api(config: dict[str, Any]) -> dict[str, Any]:
311 """Convert API response to module params format.
312
313 Args:
314 config: The API response config dictionary.
315
316 Returns:
317 Dictionary with module parameter names and normalized values.
318 """
319 phases = []
320 for phase in config.get("phases", []) or []:
321 phases.append(_map_phase_from_api(phase))
322
323 return {
324 "name": unquote(config.get("name", "")),
325 "description": unquote(config.get("description", "")),
326 "template_status": config.get("template_status", "draft"),
327 "phases": phases,
328 }
329
330
331 class ActionModule(ActionBase):
332 """Action module for managing Splunk ES response plans."""
333
334 def __init__(self, *args: Any, **kwargs: Any) -> None:
335 super().__init__(*args, **kwargs)
336 self._result = None
337 self.module_name = "response_plan"
338 self.api_namespace = DEFAULT_API_NAMESPACE
339 self.api_user = DEFAULT_API_USER
340 self.api_app = DEFAULT_API_APP
341 self.api_object = None # Will be built dynamically
342
343 def fail_json(self, msg: str) -> None:
344 """Raise an AnsibleActionFail with a cleaned up message.
345
346 Args:
347 msg: The message for the failure.
348
349 Raises:
350 AnsibleActionFail: Always raised with the provided message.
351 """
352 msg = msg.replace("(basic.py)", self._task.action)
353 raise AnsibleActionFail(msg)
354
355 def _build_api_path(self) -> str:
356 """Build the response plans API path from configured components.
357
358 Returns:
359 The complete response plans API path.
360 """
361 return _build_response_plan_api_path(self.api_namespace, self.api_user, self.api_app)
362
363 def _configure_api(self) -> None:
364 """Configure API path components from task arguments."""
365 self.api_namespace = self._task.args.get("api_namespace", DEFAULT_API_NAMESPACE)
366 self.api_user = self._task.args.get("api_user", DEFAULT_API_USER)
367 self.api_app = self._task.args.get("api_app", DEFAULT_API_APP)
368 self.api_object = self._build_api_path()
369 display.vv(f"splunk_response_plan: using API path: {self.api_object}")
370
371 def _build_response_plan_params(self) -> dict[str, Any]:
372 """Build response plan dictionary from task arguments.
373
374 Returns:
375 Dictionary containing response plan parameters from task args.
376 """
377 response_plan = {}
378
379 name = self._task.args.get("name")
380 if name:
381 response_plan["name"] = name
382
383 param_keys = [
384 "description",
385 "template_status",
386 "phases",
387 ]
388 for key in param_keys:
389 value = self._task.args.get(key)
390 if value is not None:
391 response_plan[key] = value
392
393 return response_plan
394
395 def _set_result_message(self, action: str, changed: bool) -> None:
396 """Set the appropriate result message based on check mode and action.
397
398 Args:
399 action: The action performed (created, updated, deleted).
400 changed: Whether the operation resulted in changes.
401 """
402 if self._task.check_mode:
403 if changed:
404 self._result["msg"] = f"Check mode: would {action.rstrip('ed')}e response plan"
405 else:
406 self._result["msg"] = "Check mode: no changes required"
407 else:
408 if changed:
409 self._result["msg"] = f"Response plan {action} successfully"
410 else:
411 self._result["msg"] = "No changes required"
412
413 def _validate_unique_phase_names(
414 self,
415 phases: list[dict[str, Any]],
416 ) -> list[str]:
417 """Validate that all phase names are unique within the response plan.
418
419 Args:
420 phases: List of phase dictionaries.
421
422 Returns:
423 List of error messages for any duplicate phase names found.
424 """
425 errors = []
426 phase_names: dict[str, int] = {}
427
428 for phase in phases or []:
429 phase_name = phase.get("name", "")
430 if phase_name in phase_names:
431 errors.append(f"Duplicate phase name '{phase_name}' found in response plan")
432 else:
433 phase_names[phase_name] = 1
434
435 return errors
436
437 def _validate_unique_task_names(
438 self,
439 phases: list[dict[str, Any]],
440 ) -> list[str]:
441 """Validate that all task names are unique within each phase.
442
443 Args:
444 phases: List of phase dictionaries containing tasks.
445
446 Returns:
447 List of error messages for any duplicate task names found.
448 """
449 errors = []
450
451 for phase in phases or []:
452 phase_name = phase.get("name", "")
453 task_names: dict[str, int] = {}
454
455 for task in phase.get("tasks", []) or []:
456 task_name = task.get("name", "")
457 if task_name in task_names:
458 errors.append(
459 f"Duplicate task name '{task_name}' found in phase '{phase_name}'",
460 )
461 else:
462 task_names[task_name] = 1
463
464 return errors
465
466 def _validate_response_plan(
467 self,
468 response_plan: dict[str, Any],
469 ) -> list[str]:
470 """Validate response plan structure for uniqueness constraints.
471
472 Checks for:
473 - Duplicate phase names within the response plan
474 - Duplicate task names within each phase
475
476 Args:
477 response_plan: The response plan parameters to validate.
478
479 Returns:
480 List of validation error messages. Empty list if valid.
481 """
482 errors = []
483 phases = response_plan.get("phases", [])
484
485 errors.extend(self._validate_unique_phase_names(phases))
486 errors.extend(self._validate_unique_task_names(phases))
487
488 return errors
489
490 def get_response_plan_by_name(
491 self,
492 conn_request: SplunkRequest,
493 name: str,
494 ) -> Optional[dict[str, Any]]:
495 """Get an existing response plan by its name.
496
497 Args:
498 conn_request: The SplunkRequest instance.
499 name: The response plan name to search for.
500
501 Returns:
502 The existing response plan if found, None otherwise.
503 """
504 display.vv(f"splunk_response_plan: looking up response plan by name: {name}")
505
506 response = conn_request.get_by_path(self.api_object)
507
508 if not response or "items" not in response:
509 display.vv("splunk_response_plan: no response plans found")
510 return None
511
512 plans = response.get("items", [])
513
514 # Find response plan by name
515 for plan in plans:
516 if plan.get("name") == name:
517 display.vv(f"splunk_response_plan: found response plan with id: {plan.get('id')}")
518 return plan
519
520 display.vv(f"splunk_response_plan: no response plan found with name: {name}")
521 return None
522
523 def _post_response_plan(
524 self,
525 conn_request: SplunkRequest,
526 payload: dict[str, Any],
527 ) -> dict[str, Any]:
528 """Send response plan payload to API for creation.
529
530 Args:
531 conn_request: The SplunkRequest instance.
532 payload: The response plan API payload.
533
534 Returns:
535 Parsed response plan from API response.
536 """
537 display.vvv(f"splunk_response_plan: posting to {self.api_object}")
538 display.vvv(f"splunk_response_plan: payload: {payload}")
539 api_response = conn_request.create_update(self.api_object, data=payload, json_payload=True)
540
541 after = {}
542 if api_response:
543 display.vvv(f"splunk_response_plan: API response: {api_response}")
544 after = _map_response_plan_from_api(api_response)
545
546 return after
547
548 def _post_update(
549 self,
550 conn_request: SplunkRequest,
551 ref_id: str,
552 payload: dict[str, Any],
553 ) -> dict[str, Any]:
554 """Send response plan payload to API for update.
555
556 Args:
557 conn_request: The SplunkRequest instance.
558 ref_id: The reference ID of the response plan to update.
559 payload: The response plan API payload.
560
561 Returns:
562 Parsed response plan from API response.
563 """
564 update_url = _build_response_plan_update_path(
565 ref_id,
566 self.api_namespace,
567 self.api_user,
568 self.api_app,
569 )
570
571 display.vvv(f"splunk_response_plan: posting update to {update_url}")
572 display.vvv(f"splunk_response_plan: update payload: {payload}")
573
574 api_response = conn_request.create_update(
575 update_url,
576 data=payload,
577 json_payload=True,
578 )
579
580 after = {}
581 if api_response:
582 display.vvv(f"splunk_response_plan: update API response: {api_response}")
583 after = _map_response_plan_from_api(api_response)
584
585 return after
586
587 def create_response_plan(
588 self,
589 conn_request: SplunkRequest,
590 response_plan: dict[str, Any],
591 ) -> tuple[dict[str, Any], bool]:
592 """Create a new response plan.
593
594 Args:
595 conn_request: The SplunkRequest instance.
596 response_plan: The response plan parameters.
597
598 Returns:
599 Tuple of (result_dict, changed).
600 """
601 name = response_plan.get("name", "")
602 display.v(f"splunk_response_plan: creating new response plan: {name}")
603
604 # Build API payload (no existing data for create)
605 payload = _map_response_plan_to_api(response_plan)
606
607 if self._task.check_mode:
608 display.v("splunk_response_plan: check mode - would create response plan")
609 after = _map_response_plan_from_api(payload)
610 return {"before": None, "after": after}, True
611
612 after = self._post_response_plan(conn_request, payload)
613
614 display.v("splunk_response_plan: created response plan successfully")
615 return {"before": None, "after": after}, True
616
617 def update_response_plan(
618 self,
619 conn_request: SplunkRequest,
620 existing: dict[str, Any],
621 response_plan: dict[str, Any],
622 ) -> tuple[dict[str, Any], bool]:
623 """Update an existing response plan.
624
625 Args:
626 conn_request: The SplunkRequest instance.
627 existing: The existing response plan from API.
628 response_plan: The desired response plan parameters.
629
630 Returns:
631 Tuple of (result_dict, changed).
632 """
633 ref_id = existing.get("id")
634 name = response_plan.get("name", "")
635 display.v(f"splunk_response_plan: updating response plan: {name} (id: {ref_id})")
636
637 # Map existing to module format for before state
638 before = _map_response_plan_from_api(existing)
639
640 # Build API payload with ID matching from existing data
641 payload = _map_response_plan_to_api(response_plan, existing)
642
643 # Map payload back to module format for comparison
644 desired = _map_response_plan_from_api(payload)
645
646 # Check if there are any differences
647 if before == desired:
648 display.v("splunk_response_plan: no changes needed")
649 return {"before": before, "after": before}, False
650
651 if self._task.check_mode:
652 display.v("splunk_response_plan: check mode - would update response plan")
653 return {"before": before, "after": desired}, True
654
655 after = self._post_update(conn_request, ref_id, payload)
656
657 display.v("splunk_response_plan: updated response plan successfully")
658 return {"before": before, "after": after}, True
659
660 def delete_response_plan(
661 self,
662 conn_request: SplunkRequest,
663 existing: dict[str, Any],
664 ) -> tuple[dict[str, Any], bool]:
665 """Delete an existing response plan.
666
667 Args:
668 conn_request: The SplunkRequest instance.
669 existing: The existing response plan from API.
670
671 Returns:
672 Tuple of (result_dict, changed).
673 """
674 ref_id = existing.get("id")
675 name = existing.get("name", "")
676 display.v(f"splunk_response_plan: deleting response plan: {name} (id: {ref_id})")
677
678 # Map existing to module format for before state
679 before = _map_response_plan_from_api(existing)
680
681 if self._task.check_mode:
682 display.v("splunk_response_plan: check mode - would delete response plan")
683 return {"before": before, "after": None}, True
684
685 delete_url = _build_response_plan_update_path(
686 ref_id,
687 self.api_namespace,
688 self.api_user,
689 self.api_app,
690 )
691
692 display.vvv(f"splunk_response_plan: deleting at {delete_url}")
693 conn_request.delete_by_path(delete_url)
694
695 display.v("splunk_response_plan: deleted response plan successfully")
696 return {"before": before, "after": None}, True
697
698 def _handle_present(
699 self,
700 conn_request: SplunkRequest,
701 existing: Optional[dict[str, Any]],
702 response_plan: dict[str, Any],
703 ) -> bool:
704 """Handle state=present operation.
705
706 Args:
707 conn_request: The SplunkRequest instance.
708 existing: The existing response plan if found, None otherwise.
709 response_plan: The desired response plan parameters.
710
711 Returns:
712 True if operation completed successfully, False if error occurred.
713 """
714 # Validate phases required for present state
715 if not response_plan.get("phases"):
716 self._result["failed"] = True
717 self._result["msg"] = "Missing required parameter: phases (required when state=present)"
718 return False
719
720 # Validate uniqueness of phase and task names
721 validation_errors = self._validate_response_plan(response_plan)
722 if validation_errors:
723 self._result["failed"] = True
724 self._result["msg"] = "Validation failed: " + "; ".join(validation_errors)
725 display.v(f"splunk_response_plan: validation failed: {validation_errors}")
726 return False
727
728 if existing:
729 # Update existing response plan
730 result, changed = self.update_response_plan(conn_request, existing, response_plan)
731 self._result[self.module_name] = result
732 self._result["changed"] = changed
733 self._set_result_message("updated", changed)
734 else:
735 # Create new response plan
736 result, changed = self.create_response_plan(conn_request, response_plan)
737 self._result[self.module_name] = result
738 self._result["changed"] = changed
739 self._set_result_message("created", changed)
740
741 return True
742
743 def _handle_absent(
744 self,
745 conn_request: SplunkRequest,
746 existing: Optional[dict[str, Any]],
747 ) -> None:
748 """Handle state=absent operation.
749
750 Args:
751 conn_request: The SplunkRequest instance.
752 existing: The existing response plan if found, None otherwise.
753 """
754 if not existing:
755 # Already absent, nothing to do
756 display.v("splunk_response_plan: response plan not found, already absent")
757 self._result[self.module_name] = {"before": None, "after": None}
758 self._result["changed"] = False
759 self._result["msg"] = "Response plan not found, already absent"
760 return
761
762 # Delete existing response plan
763 result, changed = self.delete_response_plan(conn_request, existing)
764 self._result[self.module_name] = result
765 self._result["changed"] = changed
766 self._set_result_message("deleted", changed)
767
768 def run(self, tmp=None, task_vars=None):
769 """Execute the action module."""
770 self._supports_check_mode = True
771 self._result = super().run(tmp, task_vars)
772
773 display.v("splunk_response_plan: starting module execution")
774
775 # Validate arguments
776 if not check_argspec(self, self._result, DOCUMENTATION):
777 display.v(
778 f"splunk_response_plan: argument validation failed: {self._result.get('msg')}",
779 )
780 return self._result
781
782 # Initialize result structure
783 self._result[self.module_name] = {}
784 self._result["changed"] = False
785
786 self._configure_api()
787
788 # Extract parameters
789 name = self._task.args.get("name")
790 state = self._task.args.get("state", "present")
791 response_plan = self._build_response_plan_params()
792
793 display.vv(f"splunk_response_plan: name: {name}")
794 display.vv(f"splunk_response_plan: state: {state}")
795 display.vvv(f"splunk_response_plan: response_plan parameters: {response_plan}")
796
797 # Validate name is provided
798 if not name:
799 self._result["failed"] = True
800 self._result["msg"] = "Missing required parameter: name"
801 return self._result
802
803 # Setup connection
804 conn = Connection(self._connection.socket_path)
805 conn_request = SplunkRequest(
806 action_module=self,
807 connection=conn,
808 not_rest_data_keys=["state", "api_namespace", "api_user", "api_app"],
809 )
810
811 # Lookup existing response plan by name
812 existing = self.get_response_plan_by_name(conn_request, name)
813
814 # Route based on state
815 if state == "absent":
816 self._handle_absent(conn_request, existing)
817 elif not self._handle_present(conn_request, existing, response_plan):
818 # _handle_present returns False on validation failure
819 return self._result
820
821 display.v(f"splunk_response_plan: completed with changed={self._result['changed']}")
822 return self._result