Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_utm_utils.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c) 2018, Johannes Brunswicker <[email protected]>
8 #
9 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
10 # SPDX-License-Identifier: BSD-2-Clause
11
12 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
13 # Do not use this from other collections or standalone plugins/modules!
14
15 from __future__ import annotations
16
17 import json
18 import typing as t
19 from http import HTTPStatus
20
21 from ansible.module_utils.basic import AnsibleModule
22 from ansible.module_utils.urls import fetch_url
23
24
25 class UTMModuleConfigurationError(Exception):
26 def __init__(self, msg: str, **args):
27 super().__init__(self, msg)
28 self.msg = msg
29 self.module_fail_args = args
30
31 def do_fail(self, module: AnsibleModule) -> t.NoReturn:
32 module.fail_json(msg=self.msg, other=self.module_fail_args)
33
34
35 class UTMModule(AnsibleModule):
36 """
37 This is a helper class to construct any UTM Module. This will automatically add the utm host, port, token,
38 protocol, validate_certs and state field to the module. If you want to implement your own sophos utm module
39 just initialize this UTMModule class and define the Payload fields that are needed for your module.
40 See the other modules like utm_aaa_group for example.
41 """
42
43 def __init__(
44 self,
45 argument_spec,
46 bypass_checks=False,
47 no_log=False,
48 mutually_exclusive=None,
49 required_together=None,
50 required_one_of=None,
51 add_file_common_args=False,
52 supports_check_mode=False,
53 required_if=None,
54 ):
55 default_specs = dict(
56 headers=dict(type="dict", required=False, default={}),
57 utm_host=dict(type="str", required=True),
58 utm_port=dict(type="int", default=4444),
59 utm_token=dict(type="str", required=True, no_log=True),
60 utm_protocol=dict(type="str", required=False, default="https", choices=["https", "http"]),
61 validate_certs=dict(type="bool", required=False, default=True),
62 state=dict(default="present", choices=["present", "absent"]),
63 )
64 super().__init__(
65 self._merge_specs(default_specs, argument_spec),
66 bypass_checks,
67 no_log,
68 mutually_exclusive,
69 required_together,
70 required_one_of,
71 add_file_common_args,
72 supports_check_mode,
73 required_if,
74 )
75
76 def _merge_specs(self, default_specs, custom_specs):
77 result = default_specs.copy()
78 result.update(custom_specs)
79 return result
80
81
82 class UTM:
83 def __init__(self, module: UTMModule, endpoint, change_relevant_keys, info_only=False):
84 """
85 Initialize UTM Class
86 :param module: The Ansible module
87 :param endpoint: The corresponding endpoint to the module
88 :param change_relevant_keys: The keys of the object to check for changes
89 :param info_only: When implementing an info module, set this to true. Will allow access to the info method only
90 """
91 self.info_only = info_only
92 self.module = module
93 self.request_url = f"{module.params.get('utm_protocol')}://{module.params.get('utm_host')}:{module.params.get('utm_port')}/api/objects/{endpoint}/"
94
95 """
96 The change_relevant_keys will be checked for changes to determine whether the object needs to be updated
97 """
98 self.change_relevant_keys = change_relevant_keys
99 self.module.params["url_username"] = "token"
100 self.module.params["url_password"] = module.params.get("utm_token")
101 if all(elem in self.change_relevant_keys for elem in module.params.keys()):
102 raise UTMModuleConfigurationError(
103 f"The keys {self.change_relevant_keys} to check are not in the modules keys:\n{list(module.params.keys())}"
104 )
105
106 def execute(self):
107 try:
108 if not self.info_only:
109 if self.module.params.get("state") == "present":
110 self._add()
111 elif self.module.params.get("state") == "absent":
112 self._remove()
113 else:
114 self._info()
115 except Exception as e:
116 self.module.fail_json(msg=f"{e}")
117
118 def _info(self):
119 """
120 returns the info for an object in utm
121 """
122 info, result = self._lookup_entry(self.module, self.request_url)
123 if info["status"] >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
124 self.module.fail_json(result=json.loads(info))
125 else:
126 if result is None:
127 self.module.exit_json(changed=False)
128 else:
129 self.module.exit_json(result=result, changed=False)
130
131 def _add(self):
132 """
133 adds or updates a host object on utm
134 """
135
136 combined_headers = self._combine_headers()
137
138 is_changed = False
139 info, result = self._lookup_entry(self.module, self.request_url)
140 if info["status"] >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
141 self.module.fail_json(result=json.loads(info))
142 else:
143 data_as_json_string = self.module.jsonify(self.module.params)
144 if result is None:
145 response, info = fetch_url(
146 self.module, self.request_url, method="POST", headers=combined_headers, data=data_as_json_string
147 )
148 if info["status"] >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
149 self.module.fail_json(msg=json.loads(info["body"]))
150 is_changed = True
151 result = self._clean_result(json.loads(response.read()))
152 else:
153 if self._is_object_changed(self.change_relevant_keys, self.module, result):
154 response, info = fetch_url(
155 self.module,
156 self.request_url + result["_ref"],
157 method="PUT",
158 headers=combined_headers,
159 data=data_as_json_string,
160 )
161 if info["status"] >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
162 self.module.fail_json(msg=json.loads(info["body"]))
163 is_changed = True
164 result = self._clean_result(json.loads(response.read()))
165 self.module.exit_json(result=result, changed=is_changed)
166
167 def _combine_headers(self):
168 """
169 This will combine a header default with headers that come from the module declaration
170 :return: A combined headers dict
171 """
172 default_headers = {"Accept": "application/json", "Content-type": "application/json"}
173 if self.module.params.get("headers") is not None:
174 result = default_headers.copy()
175 result.update(self.module.params.get("headers"))
176 else:
177 result = default_headers
178 return result
179
180 def _remove(self):
181 """
182 removes an object from utm
183 """
184 is_changed = False
185 info, result = self._lookup_entry(self.module, self.request_url)
186 if result is not None:
187 response, info = fetch_url(
188 self.module,
189 self.request_url + result["_ref"],
190 method="DELETE",
191 headers={"Accept": "application/json", "X-Restd-Err-Ack": "all"},
192 data=self.module.jsonify(self.module.params),
193 )
194 if info["status"] >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
195 self.module.fail_json(msg=json.loads(info["body"]))
196 else:
197 is_changed = True
198 self.module.exit_json(changed=is_changed)
199
200 def _lookup_entry(self, module, request_url):
201 """
202 Lookup for existing entry
203 :param module:
204 :param request_url:
205 :return:
206 """
207 response, info = fetch_url(module, request_url, method="GET", headers={"Accept": "application/json"})
208 result = None
209 if response is not None:
210 results = json.loads(response.read())
211 result = next((d for d in results if d["name"] == module.params.get("name")), None)
212 return info, result
213
214 def _clean_result(self, result):
215 """
216 Will clean the result from irrelevant fields
217 :param result: The result from the query
218 :return: The modified result
219 """
220 del result["utm_host"]
221 del result["utm_port"]
222 del result["utm_token"]
223 del result["utm_protocol"]
224 del result["validate_certs"]
225 del result["url_username"]
226 del result["url_password"]
227 del result["state"]
228 return result
229
230 def _is_object_changed(self, keys, module, result):
231 """
232 Check if my object is changed
233 :param keys: The keys that will determine if an object is changed
234 :param module: The module
235 :param result: The result from the query
236 :return:
237 """
238 return any(module.params.get(key) != result[key] for key in keys)