Debian Codegraph @

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

raw
1 # Copyright 2026 Red Hat Inc.
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 """
5 The action plugin file for splunk_investigation_info
6 """
7
8 from typing import Any, Optional
9
10 from ansible.errors import AnsibleActionFail
11 from ansible.module_utils.connection import Connection
12 from ansible.plugins.action import ActionBase
13 from ansible.utils.display import Display
14
15 from ansible_collections.splunk.es.plugins.module_utils.investigation import (
16 build_investigation_api_path,
17 map_investigation_from_api,
18 )
19 from ansible_collections.splunk.es.plugins.module_utils.splunk import (
20 SplunkRequest,
21 check_argspec,
22 )
23 from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import (
24 DEFAULT_API_APP,
25 DEFAULT_API_NAMESPACE,
26 DEFAULT_API_USER,
27 )
28 from ansible_collections.splunk.es.plugins.modules.splunk_investigation_info import (
29 DOCUMENTATION,
30 )
31
32
33 # Initialize display for debug output
34 display = Display()
35
36
37 class ActionModule(ActionBase):
38 """Action module for querying Splunk ES investigations."""
39
40 def __init__(self, *args: Any, **kwargs: Any) -> None:
41 super().__init__(*args, **kwargs)
42 self._result = None
43 # API path components - will be set in run() from task args
44 self.api_namespace = DEFAULT_API_NAMESPACE
45 self.api_user = DEFAULT_API_USER
46 self.api_app = DEFAULT_API_APP
47 self.api_object = None # Will be built dynamically
48
49 def fail_json(self, msg: str) -> None:
50 """Raise an AnsibleActionFail with a cleaned up message.
51
52 Args:
53 msg: The message for the failure.
54
55 Raises:
56 AnsibleActionFail: Always raised with the provided message.
57 """
58 msg = msg.replace("(basic.py)", self._task.action)
59 raise AnsibleActionFail(msg)
60
61 def _build_api_path(self) -> str:
62 """Build the investigations API path from configured components.
63
64 Returns:
65 The complete investigations API path.
66 """
67 return build_investigation_api_path(self.api_namespace, self.api_user, self.api_app)
68
69 def _build_query_params(self) -> Optional[dict[str, Any]]:
70 """Build query params dict with create_time_min/create_time_max/limit if provided.
71
72 Returns:
73 Dict with query params if any are set, None otherwise.
74 """
75 query_params: dict[str, Any] = {}
76 create_time_min = self._task.args.get("create_time_min")
77 create_time_max = self._task.args.get("create_time_max")
78 limit = self._task.args.get("limit")
79
80 if create_time_min:
81 query_params["create_time_min"] = create_time_min
82 if create_time_max:
83 query_params["create_time_max"] = create_time_max
84 if limit:
85 query_params["limit"] = limit
86
87 return query_params if query_params else None
88
89 def get_investigation_by_id(
90 self,
91 conn_request: SplunkRequest,
92 ref_id: str,
93 ) -> dict[str, Any]:
94 """Get an existing investigation by its reference ID.
95
96 Args:
97 conn_request: The SplunkRequest instance.
98 ref_id: The reference ID (investigation ID) to search for.
99
100 Returns:
101 The existing investigation if found, empty dict otherwise.
102 """
103 display.vv(f"splunk_investigation_info: getting investigation by ref_id: {ref_id}")
104
105 # Use the ids query parameter to filter by investigation ID
106 query_params = {"ids": ref_id}
107
108 # Add time/limit filters if provided
109 extra_params = self._build_query_params()
110 if extra_params:
111 query_params.update(extra_params)
112
113 response = conn_request.get_by_path(self.api_object, query_params=query_params)
114
115 search_result = {}
116
117 # API returns a list, get the first matching investigation
118 if response and isinstance(response, list) and len(response) > 0:
119 display.vvv(f"splunk_investigation_info: raw API response: {response}")
120 search_result = map_investigation_from_api(response[0])
121 display.vv(f"splunk_investigation_info: found investigation: {search_result}")
122 else:
123 display.vv(f"splunk_investigation_info: no investigation found with ref_id: {ref_id}")
124
125 return search_result
126
127 def get_all_investigations(self, conn_request: SplunkRequest) -> list[dict[str, Any]]:
128 """Get all investigations from the API.
129
130 Args:
131 conn_request: The SplunkRequest instance.
132
133 Returns:
134 List of all investigations.
135 """
136 display.vv("splunk_investigation_info: fetching all investigations")
137
138 query_params = self._build_query_params()
139 display.vv(f"splunk_investigation_info: query_params={query_params}")
140
141 response = conn_request.get_by_path(self.api_object, query_params=query_params)
142
143 investigations = []
144 if response:
145 display.vvv(f"splunk_investigation_info: raw API response type: {type(response)}")
146
147 # API returns a list of investigations directly
148 if isinstance(response, list):
149 for investigation in response:
150 if investigation:
151 mapped = map_investigation_from_api(investigation)
152 if mapped:
153 investigations.append(mapped)
154
155 display.vv(f"splunk_investigation_info: found {len(investigations)} investigations")
156
157 return investigations
158
159 def filter_investigations_by_name(
160 self,
161 investigations: list[dict[str, Any]],
162 name: str,
163 ) -> list[dict[str, Any]]:
164 """Filter investigations by exact name match.
165
166 Args:
167 investigations: List of investigations to filter.
168 name: The name to match.
169
170 Returns:
171 Filtered list of investigations.
172 """
173 display.vv(f"splunk_investigation_info: filtering investigations by name: {name}")
174
175 filtered = [inv for inv in investigations if inv.get("name") == name]
176
177 display.vv(
178 f"splunk_investigation_info: found {len(filtered)} investigations with matching name",
179 )
180 return filtered
181
182 def run(self, tmp=None, task_vars=None):
183 """Execute the action module."""
184 self._supports_check_mode = True
185 self._result = super().run(tmp, task_vars)
186
187 display.v("splunk_investigation_info: starting module execution")
188
189 # Validate arguments
190 if not check_argspec(self, self._result, DOCUMENTATION):
191 display.v(
192 f"splunk_investigation_info: argument validation failed: {self._result.get('msg')}",
193 )
194 return self._result
195
196 # Get API path configuration from task args
197 self.api_namespace = self._task.args.get("api_namespace", DEFAULT_API_NAMESPACE)
198 self.api_user = self._task.args.get("api_user", DEFAULT_API_USER)
199 self.api_app = self._task.args.get("api_app", DEFAULT_API_APP)
200
201 # Build the API path
202 self.api_object = self._build_api_path()
203 display.vv(f"splunk_investigation_info: using API path: {self.api_object}")
204
205 # Setup connection
206 conn = Connection(self._connection.socket_path)
207 conn_request = SplunkRequest(
208 action_module=self,
209 connection=conn,
210 not_rest_data_keys=[
211 "investigation_ref_id",
212 "name",
213 "create_time_min",
214 "create_time_max",
215 "limit",
216 "api_namespace",
217 "api_user",
218 "api_app",
219 ],
220 )
221
222 # Get query parameters
223 ref_id = self._task.args.get("investigation_ref_id")
224 name = self._task.args.get("name")
225
226 try:
227 if ref_id:
228 # Query specific investigation by ref_id
229 display.v(f"splunk_investigation_info: querying by ref_id: {ref_id}")
230 investigation = self.get_investigation_by_id(conn_request, ref_id)
231 # Return as list for consistency
232 self._result["investigations"] = [investigation] if investigation else []
233
234 elif name:
235 # Query all investigations and filter by name
236 display.v(f"splunk_investigation_info: querying by name: {name}")
237 all_investigations = self.get_all_investigations(conn_request)
238 self._result["investigations"] = self.filter_investigations_by_name(
239 all_investigations,
240 name,
241 )
242
243 else:
244 # Return all investigations
245 display.v("splunk_investigation_info: querying all investigations")
246 self._result["investigations"] = self.get_all_investigations(conn_request)
247
248 self._result["changed"] = False
249 display.v(
250 f"splunk_investigation_info: returning {len(self._result['investigations'])} "
251 "investigation(s)",
252 )
253
254 except Exception as e:
255 error_msg = str(e)
256 if "404" in error_msg or "not found" in error_msg.lower():
257 # Handle 404 gracefully - return empty list
258 self._result["changed"] = False
259 self._result["investigations"] = []
260 display.v("splunk_investigation_info: no investigations found (404)")
261 else:
262 self.fail_json(
263 msg=f"Failed to query investigation(s): {error_msg}",
264 )
265
266 return self._result