| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Splunk module utilities for Ansible.""" |
| 3 |
|
| 4 |
# (c) 2018, Adam Miller ([email protected]) |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
import json |
| 8 |
|
| 9 |
|
| 10 |
try: |
| 11 |
from ssl import CertificateError |
| 12 |
except ImportError: |
| 13 |
from backports.ssl_match_hostname import CertificateError |
| 14 |
|
| 15 |
from ansible.module_utils.common.text.converters import to_text |
| 16 |
from ansible.module_utils.connection import ConnectionError as AnsibleConnectionError |
| 17 |
from ansible.module_utils.six.moves.urllib.parse import urlencode |
| 18 |
from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import ( |
| 19 |
AnsibleArgSpecValidator, |
| 20 |
) |
| 21 |
|
| 22 |
from ansible_collections.splunk.es.plugins.module_utils import dict_utils as utils |
| 23 |
|
| 24 |
|
| 25 |
def check_argspec(action_module, result, documentation): |
| 26 |
"""Validate module arguments against the argspec. |
| 27 |
|
| 28 |
Common helper function for action plugins to validate arguments. |
| 29 |
|
| 30 |
Args: |
| 31 |
action_module: The action plugin instance (self in ActionModule). |
| 32 |
result: The result dictionary to update on validation failure. |
| 33 |
documentation: The DOCUMENTATION string from the module. |
| 34 |
|
| 35 |
Returns: |
| 36 |
True if validation passed, False if validation failed. |
| 37 |
""" |
| 38 |
aav = AnsibleArgSpecValidator( |
| 39 |
data=utils.remove_empties(action_module._task.args), |
| 40 |
schema=documentation, |
| 41 |
schema_format="doc", |
| 42 |
name=action_module._task.action, |
| 43 |
) |
| 44 |
valid, errors, action_module._task.args = aav.validate() |
| 45 |
if not valid: |
| 46 |
result["failed"] = True |
| 47 |
result["msg"] = errors |
| 48 |
return False |
| 49 |
return True |
| 50 |
|
| 51 |
|
| 52 |
class SplunkRequest: |
| 53 |
"""Handle HTTP requests to the Splunk REST API.""" |
| 54 |
|
| 55 |
def __init__( |
| 56 |
self, |
| 57 |
action_module, |
| 58 |
connection, |
| 59 |
keymap=None, |
| 60 |
not_rest_data_keys=None, |
| 61 |
): |
| 62 |
"""Initialize SplunkRequest for action plugin usage. |
| 63 |
|
| 64 |
:param action_module: The action plugin module instance |
| 65 |
:param connection: The connection object to use for API requests |
| 66 |
:param keymap: Optional mapping of module params to API params |
| 67 |
:param not_rest_data_keys: List of keys to exclude from REST data |
| 68 |
""" |
| 69 |
self.connection = connection |
| 70 |
self.connection.load_platform_plugins("splunk.es.splunk") |
| 71 |
self.module = action_module |
| 72 |
|
| 73 |
# The Splunk REST API endpoints often use keys that aren't pythonic so |
| 74 |
# we need to handle that with a mapping to allow keys to be proper |
| 75 |
# variables in the module argspec |
| 76 |
if keymap is None: |
| 77 |
self.keymap = {} |
| 78 |
else: |
| 79 |
self.keymap = keymap |
| 80 |
|
| 81 |
# This allows us to exclude specific argspec keys from being included by |
| 82 |
# the rest data that don't follow the splunk_* naming convention |
| 83 |
if not_rest_data_keys is None: |
| 84 |
self.not_rest_data_keys = [] |
| 85 |
else: |
| 86 |
self.not_rest_data_keys = not_rest_data_keys |
| 87 |
self.not_rest_data_keys.append("validate_certs") |
| 88 |
|
| 89 |
def _httpapi_error_handle(self, method, uri, payload=None): |
| 90 |
try: |
| 91 |
code, response = self.connection.send_request( |
| 92 |
method, |
| 93 |
uri, |
| 94 |
payload=payload, |
| 95 |
) |
| 96 |
|
| 97 |
if code == 404: |
| 98 |
if to_text("Object not found") in to_text(response) or to_text( |
| 99 |
"Could not find object", |
| 100 |
) in to_text(response): |
| 101 |
return {} |
| 102 |
|
| 103 |
if not 200 <= code < 300: |
| 104 |
self.module.fail_json( |
| 105 |
msg=f"Splunk httpapi returned error {code} with message {response}", |
| 106 |
) |
| 107 |
return None |
| 108 |
|
| 109 |
return response |
| 110 |
|
| 111 |
except AnsibleConnectionError as e: |
| 112 |
self.module.fail_json( |
| 113 |
msg=f"connection error occurred: {e}", |
| 114 |
) |
| 115 |
return None |
| 116 |
except CertificateError as e: |
| 117 |
self.module.fail_json( |
| 118 |
msg=f"certificate error occurred: {e}", |
| 119 |
) |
| 120 |
return None |
| 121 |
except ValueError as e: |
| 122 |
try: |
| 123 |
self.module.fail_json( |
| 124 |
msg=f"certificate not found: {e}", |
| 125 |
) |
| 126 |
except AttributeError: |
| 127 |
pass |
| 128 |
return None |
| 129 |
|
| 130 |
def get(self, url, **kwargs): |
| 131 |
"""Perform a GET request to the Splunk API.""" |
| 132 |
return self._httpapi_error_handle("GET", url, **kwargs) |
| 133 |
|
| 134 |
def put(self, url, **kwargs): |
| 135 |
"""Perform a PUT request to the Splunk API.""" |
| 136 |
return self._httpapi_error_handle("PUT", url, **kwargs) |
| 137 |
|
| 138 |
def post(self, url, **kwargs): |
| 139 |
"""Perform a POST request to the Splunk API.""" |
| 140 |
return self._httpapi_error_handle("POST", url, **kwargs) |
| 141 |
|
| 142 |
def delete(self, url, **kwargs): |
| 143 |
"""Perform a DELETE request to the Splunk API.""" |
| 144 |
return self._httpapi_error_handle("DELETE", url, **kwargs) |
| 145 |
|
| 146 |
def get_data(self, config): |
| 147 |
""" |
| 148 |
Get the valid fields that should be passed to the REST API as urlencoded |
| 149 |
data so long as the argument specification to the module follows the |
| 150 |
convention: |
| 151 |
- the key to the argspec item does not start with splunk_ |
| 152 |
- the key does not exist in the not_data_keys list |
| 153 |
|
| 154 |
:param config: Configuration dictionary to transform |
| 155 |
:return: Dictionary with transformed data for REST API |
| 156 |
""" |
| 157 |
try: |
| 158 |
splunk_data = {} |
| 159 |
for param in config: |
| 160 |
if (config[param]) is not None and (param not in self.not_rest_data_keys): |
| 161 |
if param in self.keymap: |
| 162 |
splunk_data[self.keymap[param]] = config[param] |
| 163 |
else: |
| 164 |
splunk_data[param] = config[param] |
| 165 |
|
| 166 |
return splunk_data |
| 167 |
|
| 168 |
except TypeError as e: |
| 169 |
self.module.fail_json( |
| 170 |
msg=f"invalid data type provided: {e}", |
| 171 |
) |
| 172 |
return None |
| 173 |
|
| 174 |
def get_urlencoded_data(self, config): |
| 175 |
"""Get data as URL-encoded string for REST API requests.""" |
| 176 |
return urlencode(self.get_data(config)) |
| 177 |
|
| 178 |
def get_by_path(self, rest_path, query_params=None): |
| 179 |
""" |
| 180 |
Perform a GET request to a Splunk REST API path. |
| 181 |
|
| 182 |
Args: |
| 183 |
rest_path: REST API path without a leading slash. |
| 184 |
query_params: Optional dictionary of query parameters to append. |
| 185 |
Values of None are omitted. |
| 186 |
|
| 187 |
Returns: |
| 188 |
Parsed response from the httpapi connection plugin. |
| 189 |
""" |
| 190 |
params = {"output_mode": "json"} |
| 191 |
if query_params and isinstance(query_params, dict): |
| 192 |
for k, v in query_params.items(): |
| 193 |
if v is not None: |
| 194 |
params[k] = v |
| 195 |
|
| 196 |
return self.get(f"/{rest_path}?{urlencode(params, doseq=True)}") |
| 197 |
|
| 198 |
def delete_by_path(self, rest_path): |
| 199 |
""" |
| 200 |
DELETE attributes of a monitor by rest path |
| 201 |
""" |
| 202 |
|
| 203 |
return self.delete(f"/{rest_path}?output_mode=json") |
| 204 |
|
| 205 |
def create_update(self, rest_path, data, query_params=None, json_payload=False): |
| 206 |
""" |
| 207 |
Create or Update a resource in Splunk using POST. |
| 208 |
|
| 209 |
:param rest_path: The REST API path |
| 210 |
:param data: Data dictionary to send |
| 211 |
:param query_params: Optional dictionary of query parameters to append. |
| 212 |
:param json_payload: If True, send as JSON. If False, send as URL-encoded (default). |
| 213 |
:return: API response |
| 214 |
""" |
| 215 |
# Apply keymap transformation if data is a dictionary |
| 216 |
if data is not None and isinstance(data, dict): |
| 217 |
if json_payload: |
| 218 |
data = json.dumps(data) |
| 219 |
else: |
| 220 |
data = self.get_urlencoded_data(data) |
| 221 |
|
| 222 |
params = {"output_mode": "json"} |
| 223 |
if query_params and isinstance(query_params, dict): |
| 224 |
for k, v in query_params.items(): |
| 225 |
if v is not None: |
| 226 |
params[k] = v |
| 227 |
|
| 228 |
return self.post( |
| 229 |
f"/{rest_path}?{urlencode(params, doseq=True)}", |
| 230 |
payload=data, |
| 231 |
) |
| 232 |
|
| 233 |
def update_by_path(self, rest_path, data, query_params=None, json_payload=False): |
| 234 |
""" |
| 235 |
Update a resource in Splunk using PUT. |
| 236 |
|
| 237 |
:param rest_path: The REST API path (without leading slash) |
| 238 |
:param data: Data dictionary to send |
| 239 |
:param query_params: Optional dictionary of query parameters to append. |
| 240 |
:param json_payload: If True, send as JSON. If False, send as URL-encoded (default). |
| 241 |
:return: API response |
| 242 |
""" |
| 243 |
# Apply keymap transformation if data is a dictionary |
| 244 |
if data is not None and isinstance(data, dict): |
| 245 |
if json_payload: |
| 246 |
data = json.dumps(data) |
| 247 |
else: |
| 248 |
data = self.get_urlencoded_data(data) |
| 249 |
|
| 250 |
params = {"output_mode": "json"} |
| 251 |
if query_params and isinstance(query_params, dict): |
| 252 |
for k, v in query_params.items(): |
| 253 |
if v is not None: |
| 254 |
params[k] = v |
| 255 |
|
| 256 |
return self.put( |
| 257 |
f"/{rest_path}?{urlencode(params, doseq=True)}", |
| 258 |
payload=data, |
| 259 |
) |