| 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_info |
| 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 unquote |
| 29 |
from ansible.plugins.action import ActionBase |
| 30 |
from ansible.utils.display import Display |
| 31 |
|
| 32 |
from ansible_collections.splunk.es.plugins.module_utils.splunk import ( |
| 33 |
SplunkRequest, |
| 34 |
check_argspec, |
| 35 |
) |
| 36 |
from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import ( |
| 37 |
DEFAULT_API_APP, |
| 38 |
DEFAULT_API_NAMESPACE, |
| 39 |
DEFAULT_API_USER, |
| 40 |
) |
| 41 |
from ansible_collections.splunk.es.plugins.modules.splunk_response_plan_info import ( |
| 42 |
DOCUMENTATION, |
| 43 |
) |
| 44 |
|
| 45 |
|
| 46 |
# Initialize display for debug output |
| 47 |
display = Display() |
| 48 |
|
| 49 |
|
| 50 |
def _build_response_plan_api_path( |
| 51 |
namespace: str = DEFAULT_API_NAMESPACE, |
| 52 |
user: str = DEFAULT_API_USER, |
| 53 |
app: str = DEFAULT_API_APP, |
| 54 |
) -> str: |
| 55 |
"""Build the response plans API path from components. |
| 56 |
|
| 57 |
Args: |
| 58 |
namespace: The namespace portion of the path. Defaults to 'servicesNS'. |
| 59 |
user: The user portion of the path. Defaults to 'nobody'. |
| 60 |
app: The app portion of the path. Defaults to 'missioncontrol'. |
| 61 |
|
| 62 |
Returns: |
| 63 |
The complete response plans API path. |
| 64 |
""" |
| 65 |
return f"{namespace}/{user}/{app}/v1/responsetemplates" |
| 66 |
|
| 67 |
|
| 68 |
def _map_task_info_from_api(task: dict[str, Any]) -> dict[str, Any]: |
| 69 |
"""Convert single task from API format to info module format with ID. |
| 70 |
|
| 71 |
Args: |
| 72 |
task: Task dictionary from API response. |
| 73 |
|
| 74 |
Returns: |
| 75 |
Task in info module format including ID. |
| 76 |
""" |
| 77 |
# Extract searches from suggestions |
| 78 |
searches = [] |
| 79 |
suggestions = task.get("suggestions", {}) or {} |
| 80 |
for search in suggestions.get("searches", []) or []: |
| 81 |
searches.append( |
| 82 |
{ |
| 83 |
"name": unquote(search.get("name", "")), |
| 84 |
"description": unquote(search.get("description", "")), |
| 85 |
"spl": unquote(search.get("spl", "")), |
| 86 |
}, |
| 87 |
) |
| 88 |
|
| 89 |
return { |
| 90 |
"id": task.get("id", ""), |
| 91 |
"name": unquote(task.get("name", "")), |
| 92 |
"description": unquote(task.get("description", "")), |
| 93 |
"is_note_required": task.get("is_note_required", False), |
| 94 |
"owner": task.get("owner", "unassigned"), |
| 95 |
"searches": searches, |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
def _map_phase_info_from_api(phase: dict[str, Any]) -> dict[str, Any]: |
| 100 |
"""Convert single phase from API format to info module format with ID. |
| 101 |
|
| 102 |
Args: |
| 103 |
phase: Phase dictionary from API response. |
| 104 |
|
| 105 |
Returns: |
| 106 |
Phase in info module format including ID. |
| 107 |
""" |
| 108 |
tasks = [] |
| 109 |
for task in phase.get("tasks", []) or []: |
| 110 |
tasks.append(_map_task_info_from_api(task)) |
| 111 |
|
| 112 |
return { |
| 113 |
"id": phase.get("id", ""), |
| 114 |
"name": unquote(phase.get("name", "")), |
| 115 |
"tasks": tasks, |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
def _map_response_plan_info_from_api(config: dict[str, Any]) -> dict[str, Any]: |
| 120 |
"""Convert API response to info module format with all IDs. |
| 121 |
|
| 122 |
Args: |
| 123 |
config: The API response config dictionary. |
| 124 |
|
| 125 |
Returns: |
| 126 |
Dictionary with all fields including IDs for display purposes. |
| 127 |
""" |
| 128 |
phases = [] |
| 129 |
for phase in config.get("phases", []) or []: |
| 130 |
phases.append(_map_phase_info_from_api(phase)) |
| 131 |
|
| 132 |
return { |
| 133 |
"id": config.get("id", ""), |
| 134 |
"template_id": config.get("template_id", ""), |
| 135 |
"name": unquote(config.get("name", "")), |
| 136 |
"description": unquote(config.get("description", "")), |
| 137 |
"template_status": config.get("template_status", "draft"), |
| 138 |
"phases": phases, |
| 139 |
} |
| 140 |
|
| 141 |
|
| 142 |
class ActionModule(ActionBase): |
| 143 |
"""Action module for querying Splunk ES response plans.""" |
| 144 |
|
| 145 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 146 |
super().__init__(*args, **kwargs) |
| 147 |
self._result = None |
| 148 |
# API path components - will be set in run() from task args |
| 149 |
self.api_namespace = DEFAULT_API_NAMESPACE |
| 150 |
self.api_user = DEFAULT_API_USER |
| 151 |
self.api_app = DEFAULT_API_APP |
| 152 |
self.api_object = None # Will be built dynamically |
| 153 |
|
| 154 |
def fail_json(self, msg: str) -> None: |
| 155 |
"""Raise an AnsibleActionFail with a cleaned up message. |
| 156 |
|
| 157 |
Args: |
| 158 |
msg: The message for the failure. |
| 159 |
|
| 160 |
Raises: |
| 161 |
AnsibleActionFail: Always raised with the provided message. |
| 162 |
""" |
| 163 |
msg = msg.replace("(basic.py)", self._task.action) |
| 164 |
raise AnsibleActionFail(msg) |
| 165 |
|
| 166 |
def _build_api_path(self) -> str: |
| 167 |
"""Build the response plans API path from configured components. |
| 168 |
|
| 169 |
Returns: |
| 170 |
The complete response plans API path. |
| 171 |
""" |
| 172 |
return _build_response_plan_api_path(self.api_namespace, self.api_user, self.api_app) |
| 173 |
|
| 174 |
def _build_query_params(self) -> Optional[dict[str, Any]]: |
| 175 |
"""Build query params dict with limit if provided. |
| 176 |
|
| 177 |
Returns: |
| 178 |
Dict with query params if any are set, None otherwise. |
| 179 |
""" |
| 180 |
query_params: dict[str, Any] = {} |
| 181 |
|
| 182 |
limit = self._task.args.get("limit") |
| 183 |
if limit: |
| 184 |
query_params["limit"] = limit |
| 185 |
|
| 186 |
return query_params if query_params else None |
| 187 |
|
| 188 |
def get_all_response_plans(self, conn_request: SplunkRequest) -> list[dict[str, Any]]: |
| 189 |
"""Get all response plans from the API. |
| 190 |
|
| 191 |
Args: |
| 192 |
conn_request: The SplunkRequest instance. |
| 193 |
|
| 194 |
Returns: |
| 195 |
List of all response plans with IDs included. |
| 196 |
""" |
| 197 |
display.vv("splunk_response_plan_info: fetching all response plans") |
| 198 |
|
| 199 |
query_params = self._build_query_params() |
| 200 |
display.vv(f"splunk_response_plan_info: query_params={query_params}") |
| 201 |
|
| 202 |
response = conn_request.get_by_path(self.api_object, query_params=query_params) |
| 203 |
|
| 204 |
response_plans = [] |
| 205 |
if response and "items" in response: |
| 206 |
display.vvv(f"splunk_response_plan_info: raw API response type: {type(response)}") |
| 207 |
|
| 208 |
for plan in response.get("items", []): |
| 209 |
if plan: |
| 210 |
mapped = _map_response_plan_info_from_api(plan) |
| 211 |
if mapped: |
| 212 |
response_plans.append(mapped) |
| 213 |
|
| 214 |
display.vv(f"splunk_response_plan_info: found {len(response_plans)} response plans") |
| 215 |
|
| 216 |
return response_plans |
| 217 |
|
| 218 |
def filter_response_plans_by_name( |
| 219 |
self, |
| 220 |
response_plans: list[dict[str, Any]], |
| 221 |
name: str, |
| 222 |
) -> list[dict[str, Any]]: |
| 223 |
"""Filter response plans by exact name match. |
| 224 |
|
| 225 |
Args: |
| 226 |
response_plans: List of response plans to filter. |
| 227 |
name: The name to match. |
| 228 |
|
| 229 |
Returns: |
| 230 |
Filtered list of response plans. |
| 231 |
""" |
| 232 |
display.vv(f"splunk_response_plan_info: filtering response plans by name: {name}") |
| 233 |
|
| 234 |
filtered = [plan for plan in response_plans if plan.get("name") == name] |
| 235 |
|
| 236 |
display.vv( |
| 237 |
f"splunk_response_plan_info: found {len(filtered)} response plans with matching name", |
| 238 |
) |
| 239 |
return filtered |
| 240 |
|
| 241 |
def run(self, tmp=None, task_vars=None): |
| 242 |
"""Execute the action module.""" |
| 243 |
self._supports_check_mode = True |
| 244 |
self._result = super().run(tmp, task_vars) |
| 245 |
|
| 246 |
display.v("splunk_response_plan_info: starting module execution") |
| 247 |
|
| 248 |
# Validate arguments |
| 249 |
if not check_argspec(self, self._result, DOCUMENTATION): |
| 250 |
display.v( |
| 251 |
f"splunk_response_plan_info: argument validation failed: " |
| 252 |
f"{self._result.get('msg')}", |
| 253 |
) |
| 254 |
return self._result |
| 255 |
|
| 256 |
# Get API path configuration from task args |
| 257 |
self.api_namespace = self._task.args.get("api_namespace", DEFAULT_API_NAMESPACE) |
| 258 |
self.api_user = self._task.args.get("api_user", DEFAULT_API_USER) |
| 259 |
self.api_app = self._task.args.get("api_app", DEFAULT_API_APP) |
| 260 |
|
| 261 |
# Build the API path |
| 262 |
self.api_object = self._build_api_path() |
| 263 |
display.vv(f"splunk_response_plan_info: using API path: {self.api_object}") |
| 264 |
|
| 265 |
# Setup connection |
| 266 |
conn = Connection(self._connection.socket_path) |
| 267 |
conn_request = SplunkRequest( |
| 268 |
action_module=self, |
| 269 |
connection=conn, |
| 270 |
not_rest_data_keys=[ |
| 271 |
"name", |
| 272 |
"limit", |
| 273 |
"api_namespace", |
| 274 |
"api_user", |
| 275 |
"api_app", |
| 276 |
], |
| 277 |
) |
| 278 |
|
| 279 |
# Get query parameters |
| 280 |
name = self._task.args.get("name") |
| 281 |
|
| 282 |
try: |
| 283 |
if name: |
| 284 |
# Query all response plans and filter by name |
| 285 |
display.v(f"splunk_response_plan_info: querying by name: {name}") |
| 286 |
all_response_plans = self.get_all_response_plans(conn_request) |
| 287 |
self._result["response_plans"] = self.filter_response_plans_by_name( |
| 288 |
all_response_plans, |
| 289 |
name, |
| 290 |
) |
| 291 |
|
| 292 |
else: |
| 293 |
# Return all response plans |
| 294 |
display.v("splunk_response_plan_info: querying all response plans") |
| 295 |
self._result["response_plans"] = self.get_all_response_plans(conn_request) |
| 296 |
|
| 297 |
self._result["changed"] = False |
| 298 |
display.v( |
| 299 |
f"splunk_response_plan_info: returning {len(self._result['response_plans'])} " |
| 300 |
"response plan(s)", |
| 301 |
) |
| 302 |
|
| 303 |
except Exception as e: |
| 304 |
error_msg = str(e) |
| 305 |
if "404" in error_msg or "not found" in error_msg.lower(): |
| 306 |
# Handle 404 gracefully - return empty list |
| 307 |
self._result["changed"] = False |
| 308 |
self._result["response_plans"] = [] |
| 309 |
display.v("splunk_response_plan_info: no response plans found (404)") |
| 310 |
else: |
| 311 |
self.fail_json( |
| 312 |
msg=f"Failed to query response plan(s): {error_msg}", |
| 313 |
) |
| 314 |
|
| 315 |
return self._result |