Debian Codegraph @

ansible_collections/community/general/plugins/modules/manageiq_alerts.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017 Red Hat Inc.
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: manageiq_alerts
10
11 short_description: Configuration of alerts in ManageIQ
12 extends_documentation_fragment:
13 - community.general._manageiq
14 - community.general._attributes
15
16 author: Elad Alfassa (@elad661) <[email protected]>
17 description:
18 - The manageiq_alerts module supports adding, updating and deleting alerts in ManageIQ.
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24
25 options:
26 state:
27 type: str
28 description:
29 - V(absent) - alert should not exist,
30 - V(present) - alert should exist.
31 choices: ['absent', 'present']
32 default: 'present'
33 description:
34 type: str
35 description:
36 - The unique alert description in ManageIQ.
37 - Required when state is "absent" or "present".
38 resource_type:
39 type: str
40 description:
41 - The entity type for the alert in ManageIQ. Required when O(state=present).
42 choices: ['Vm', 'ContainerNode', 'MiqServer', 'Host', 'Storage', 'EmsCluster', 'ExtManagementSystem', 'MiddlewareServer']
43 expression_type:
44 type: str
45 description:
46 - Expression type.
47 default: hash
48 choices: ["hash", "miq"]
49 expression:
50 type: dict
51 description:
52 - The alert expression for ManageIQ.
53 - Can either be in the "Miq Expression" format or the "Hash Expression format".
54 - Required if O(state=present).
55 enabled:
56 description:
57 - Enable or disable the alert. Required if O(state=present).
58 type: bool
59 options:
60 type: dict
61 description:
62 - Additional alert options, such as notification type and frequency.
63 """
64
65 EXAMPLES = r"""
66 - name: Add an alert with a "hash expression" to ManageIQ
67 community.general.manageiq_alerts:
68 state: present
69 description: Test Alert 01
70 options:
71 notifications:
72 email:
73 to: ["[email protected]"]
74 from: "[email protected]"
75 resource_type: ContainerNode
76 expression:
77 eval_method: hostd_log_threshold
78 mode: internal
79 options: {}
80 enabled: true
81 manageiq_connection:
82 url: 'http://127.0.0.1:3000'
83 username: 'admin'
84 password: 'smartvm'
85 validate_certs: false # only do this when you trust the network!
86
87 - name: Add an alert with a "miq expression" to ManageIQ
88 community.general.manageiq_alerts:
89 state: present
90 description: Test Alert 02
91 options:
92 notifications:
93 email:
94 to: ["[email protected]"]
95 from: "[email protected]"
96 resource_type: Vm
97 expression_type: miq
98 expression:
99 and:
100 - CONTAINS:
101 tag: Vm.managed-environment
102 value: prod
103 - not:
104 CONTAINS:
105 tag: Vm.host.managed-environment
106 value: prod
107 enabled: true
108 manageiq_connection:
109 url: 'http://127.0.0.1:3000'
110 username: 'admin'
111 password: 'smartvm'
112 validate_certs: false # only do this when you trust the network!
113
114 - name: Delete an alert from ManageIQ
115 community.general.manageiq_alerts:
116 state: absent
117 description: Test Alert 01
118 manageiq_connection:
119 url: 'http://127.0.0.1:3000'
120 username: 'admin'
121 password: 'smartvm'
122 validate_certs: false # only do this when you trust the network!
123 """
124
125 RETURN = r"""
126 """
127
128 from ansible.module_utils.basic import AnsibleModule
129
130 from ansible_collections.community.general.plugins.module_utils._manageiq import ManageIQ, manageiq_argument_spec
131
132
133 class ManageIQAlert:
134 """Represent a ManageIQ alert. Can be initialized with both the format
135 we receive from the server and the format we get from the user.
136 """
137
138 def __init__(self, alert):
139 self.description = alert["description"]
140 self.db = alert["db"]
141 self.enabled = alert["enabled"]
142 self.options = alert["options"]
143 self.hash_expression = None
144 self.miq_expressipn = None
145
146 if "hash_expression" in alert:
147 self.hash_expression = alert["hash_expression"]
148 if "miq_expression" in alert:
149 self.miq_expression = alert["miq_expression"]
150 if "exp" in self.miq_expression:
151 # miq_expression is a field that needs a special case, because
152 # it is returned surrounded by a dict named exp even though we don't
153 # send it with that dict.
154 self.miq_expression = self.miq_expression["exp"]
155
156 def __eq__(self, other):
157 """Compare two ManageIQAlert objects"""
158 return self.__dict__ == other.__dict__
159
160
161 class ManageIQAlerts:
162 """Object to execute alert management operations in manageiq."""
163
164 def __init__(self, manageiq):
165 self.manageiq = manageiq
166
167 self.module = self.manageiq.module
168 self.api_url = self.manageiq.api_url
169 self.client = self.manageiq.client
170 self.alerts_url = f"{self.api_url}/alert_definitions"
171
172 def get_alerts(self):
173 """Get all alerts from ManageIQ"""
174 try:
175 response = self.client.get(f"{self.alerts_url}?expand=resources")
176 except Exception as e:
177 self.module.fail_json(msg=f"Failed to query alerts: {e}")
178 return response.get("resources", [])
179
180 def validate_hash_expression(self, expression):
181 """Validate a 'hash expression' alert definition"""
182 # hash expressions must have the following fields
183 for key in ["options", "eval_method", "mode"]:
184 if key not in expression:
185 msg = f"Hash expression is missing required field {key}"
186 self.module.fail_json(msg)
187
188 def create_alert_dict(self, params):
189 """Create a dict representing an alert"""
190 if params["expression_type"] == "hash":
191 # hash expression supports depends on https://github.com/ManageIQ/manageiq-api/pull/76
192 self.validate_hash_expression(params["expression"])
193 expression_type = "hash_expression"
194 else:
195 # actually miq_expression, but we call it "expression" for backwards-compatibility
196 expression_type = "expression"
197
198 # build the alret
199 alert = dict(
200 description=params["description"],
201 db=params["resource_type"],
202 options=params["options"],
203 enabled=params["enabled"],
204 )
205
206 # add the actual expression.
207 alert.update({expression_type: params["expression"]})
208
209 return alert
210
211 def add_alert(self, alert):
212 """Add a new alert to ManageIQ"""
213 try:
214 result = self.client.post(self.alerts_url, action="create", resource=alert)
215
216 msg = f"Alert {alert['description']} created successfully: {result}"
217 return dict(changed=True, msg=msg)
218 except Exception as e:
219 description = alert["description"]
220 if "Resource expression needs be specified" in str(e):
221 # Running on an older version of ManageIQ and trying to create a hash expression
222 msg = f"Creating alert {description} failed: Your version of ManageIQ does not support hash_expression"
223 else:
224 msg = f"Creating alert {description} failed: {e}"
225 self.module.fail_json(msg=msg)
226
227 def delete_alert(self, alert):
228 """Delete an alert"""
229 try:
230 result = self.client.post(f"{self.alerts_url}/{alert['id']}", action="delete")
231 msg = f"Alert {alert['description']} deleted: {result}"
232 return dict(changed=True, msg=msg)
233 except Exception as e:
234 msg = f"Deleting alert {alert['description']} failed: {e}"
235 self.module.fail_json(msg=msg)
236
237 def update_alert(self, existing_alert, new_alert):
238 """Update an existing alert with the values from `new_alert`"""
239 new_alert_obj = ManageIQAlert(new_alert)
240 if new_alert_obj == ManageIQAlert(existing_alert):
241 # no change needed - alerts are identical
242 return dict(changed=False, msg="No update needed")
243 else:
244 try:
245 url = f"{self.alerts_url}/{existing_alert['id']}"
246 result = self.client.post(url, action="edit", resource=new_alert)
247
248 # make sure that the update was indeed successful by comparing
249 # the result to the expected result.
250 if new_alert_obj == ManageIQAlert(result):
251 # success!
252 msg = f"Alert {existing_alert['description']} updated successfully: {result}"
253
254 return dict(changed=True, msg=msg)
255 else:
256 # unexpected result
257 msg = f"Updating alert {existing_alert['description']} failed, unexpected result {result}"
258
259 self.module.fail_json(msg=msg)
260
261 except Exception as e:
262 description = existing_alert["description"]
263 if "Resource expression needs be specified" in str(e):
264 # Running on an older version of ManageIQ and trying to update a hash expression
265 msg = f"Updating alert {description} failed: Your version of ManageIQ does not support hash_expression"
266 else:
267 msg = f"Updating alert {description} failed: {e}"
268 self.module.fail_json(msg=msg)
269
270
271 def main():
272 argument_spec = dict(
273 description=dict(type="str"),
274 resource_type=dict(
275 type="str",
276 choices=[
277 "Vm",
278 "ContainerNode",
279 "MiqServer",
280 "Host",
281 "Storage",
282 "EmsCluster",
283 "ExtManagementSystem",
284 "MiddlewareServer",
285 ],
286 ),
287 expression_type=dict(type="str", default="hash", choices=["miq", "hash"]),
288 expression=dict(type="dict"),
289 options=dict(type="dict"),
290 enabled=dict(type="bool"),
291 state=dict(default="present", choices=["present", "absent"]),
292 )
293 # add the manageiq connection arguments to the arguments
294 argument_spec.update(manageiq_argument_spec())
295
296 module = AnsibleModule(
297 argument_spec=argument_spec,
298 required_if=[
299 ("state", "present", ["description", "resource_type", "expression", "enabled", "options"]),
300 ("state", "absent", ["description"]),
301 ],
302 )
303
304 state = module.params["state"]
305 description = module.params["description"]
306
307 manageiq = ManageIQ(module)
308 manageiq_alerts = ManageIQAlerts(manageiq)
309
310 existing_alert = manageiq.find_collection_resource_by("alert_definitions", description=description)
311
312 # we need to add or update the alert
313 if state == "present":
314 alert = manageiq_alerts.create_alert_dict(module.params)
315
316 if not existing_alert:
317 # an alert with this description doesn't exist yet, let's create it
318 res_args = manageiq_alerts.add_alert(alert)
319 else:
320 # an alert with this description exists, we might need to update it
321 res_args = manageiq_alerts.update_alert(existing_alert, alert)
322
323 # this alert should not exist
324 elif state == "absent":
325 # if we have an alert with this description, delete it
326 if existing_alert:
327 res_args = manageiq_alerts.delete_alert(existing_alert)
328 else:
329 # it doesn't exist, and that's okay
330 msg = f"Alert '{description}' does not exist in ManageIQ"
331 res_args = dict(changed=False, msg=msg)
332
333 module.exit_json(**res_args)
334
335
336 if __name__ == "__main__":
337 main()