Debian Codegraph @

ansible_collections/splunk/es/plugins/action/splunk_response_plan_execution_info.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 plugin file for splunk_response_plan_execution_info
22 """
23
24 from typing import Any
25
26 from ansible.errors import AnsibleActionFail
27 from ansible.module_utils.connection import Connection
28 from ansible.plugins.action import ActionBase
29 from ansible.utils.display import Display
30
31 from ansible_collections.splunk.es.plugins.module_utils.response_plan_execution import (
32 map_applied_response_plan_from_api,
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_execution_info import (
44 DOCUMENTATION,
45 )
46
47
48 # Initialize display for debug output
49 display = Display()
50
51
52 class ActionModule(ActionBase):
53 """Action module for querying applied response plans on an investigation."""
54
55 def __init__(self, *args: Any, **kwargs: Any) -> None:
56 super().__init__(*args, **kwargs)
57 self._result: dict[str, Any] = {}
58 # API path components - will be set in run() from task args
59 self.api_namespace = DEFAULT_API_NAMESPACE
60 self.api_user = DEFAULT_API_USER
61 self.api_app = DEFAULT_API_APP
62
63 def fail_json(self, msg: str) -> None:
64 """Raise an AnsibleActionFail with a cleaned up message.
65
66 Args:
67 msg: The message for the failure.
68
69 Raises:
70 AnsibleActionFail: Always raised with the provided message.
71 """
72 msg = msg.replace("(basic.py)", self._task.action)
73 raise AnsibleActionFail(msg)
74
75 def _get_applied_response_plans(
76 self,
77 conn_request: SplunkRequest,
78 investigation_id: str,
79 ) -> list[dict[str, Any]]:
80 """Get all response plans applied to an investigation.
81
82 Args:
83 conn_request: The SplunkRequest instance.
84 investigation_id: The investigation UUID.
85
86 Returns:
87 List of applied response plans from the API.
88 """
89 api_path = (
90 f"{self.api_namespace}/{self.api_user}/{self.api_app}"
91 f"/v1/incidents/{investigation_id}"
92 )
93 display.vvv(f"splunk_response_plan_execution_info: GET {api_path}")
94
95 response = conn_request.get_by_path(api_path)
96 if not response:
97 return []
98
99 # Extract response_plans from the incident details
100 response_plans = response.get("response_plans")
101 if response_plans is None:
102 return []
103 return response_plans
104
105 def run(self, tmp=None, task_vars=None):
106 """Execute the action module."""
107 self._supports_check_mode = True
108 self._result = super().run(tmp, task_vars)
109
110 display.v("splunk_response_plan_execution_info: starting module execution")
111
112 # Validate arguments
113 if not check_argspec(self, self._result, DOCUMENTATION):
114 display.v(
115 f"splunk_response_plan_execution_info: argument validation failed: "
116 f"{self._result.get('msg')}",
117 )
118 return self._result
119
120 # Get API path configuration from task args
121 self.api_namespace = self._task.args.get("api_namespace", DEFAULT_API_NAMESPACE)
122 self.api_user = self._task.args.get("api_user", DEFAULT_API_USER)
123 self.api_app = self._task.args.get("api_app", DEFAULT_API_APP)
124
125 display.vv(
126 f"splunk_response_plan_execution_info: API config - "
127 f"namespace={self.api_namespace}, user={self.api_user}, app={self.api_app}",
128 )
129
130 # Get required parameter
131 investigation_id = self._task.args.get("investigation_ref_id")
132
133 if not investigation_id:
134 self._result["failed"] = True
135 self._result["msg"] = "Missing required parameter: investigation_ref_id"
136 return self._result
137
138 display.vv(
139 f"splunk_response_plan_execution_info: investigation_ref_id: {investigation_id}",
140 )
141
142 # Setup connection
143 conn = Connection(self._connection.socket_path)
144 conn_request = SplunkRequest(
145 action_module=self,
146 connection=conn,
147 not_rest_data_keys=[
148 "investigation_ref_id",
149 "api_namespace",
150 "api_user",
151 "api_app",
152 ],
153 )
154
155 try:
156 # Fetch applied response plans
157 display.v(
158 f"splunk_response_plan_execution_info: fetching applied plans for "
159 f"{investigation_id}",
160 )
161 raw_plans = self._get_applied_response_plans(conn_request, investigation_id)
162
163 # Map each plan to module format using existing utility
164 applied_plans = []
165 for plan in raw_plans:
166 mapped_plan = map_applied_response_plan_from_api(plan)
167 applied_plans.append(mapped_plan)
168
169 self._result["applied_response_plans"] = applied_plans
170 self._result["changed"] = False
171
172 display.v(
173 f"splunk_response_plan_execution_info: found {len(applied_plans)} "
174 f"applied response plan(s)",
175 )
176
177 except Exception as e:
178 error_msg = str(e)
179 if "404" in error_msg or "not found" in error_msg.lower():
180 # Handle 404 gracefully - investigation not found
181 self._result["failed"] = True
182 self._result["msg"] = f"Investigation not found: {investigation_id}"
183 else:
184 self.fail_json(
185 msg=f"Failed to query applied response plans: {error_msg}",
186 )
187
188 return self._result