Debian Codegraph @

ansible_collections/community/general/plugins/modules/manageiq_alert_profiles.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_alert_profiles
10
11 short_description: Configuration of alert profiles for 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_alert_profiles module supports adding, updating and deleting alert profiles 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 profile should not exist,
30 - V(present) - alert profile should exist.
31 choices: ['absent', 'present']
32 default: 'present'
33 name:
34 type: str
35 description:
36 - The unique alert profile name in ManageIQ.
37 required: true
38 resource_type:
39 type: str
40 description:
41 - The resource type for the alert profile in ManageIQ. Required when O(state=present).
42 choices: ['Vm', 'ContainerNode', 'MiqServer', 'Host', 'Storage', 'EmsCluster', 'ExtManagementSystem', 'MiddlewareServer']
43 alerts:
44 type: list
45 elements: str
46 description:
47 - List of alert descriptions to assign to this profile.
48 - Required if O(state=present).
49 notes:
50 type: str
51 description:
52 - Optional notes for this profile.
53 """
54
55 EXAMPLES = r"""
56 - name: Add an alert profile to ManageIQ
57 community.general.manageiq_alert_profiles:
58 state: present
59 name: Test profile
60 resource_type: ContainerNode
61 alerts:
62 - Test Alert 01
63 - Test Alert 02
64 manageiq_connection:
65 url: 'http://127.0.0.1:3000'
66 username: 'admin'
67 password: 'smartvm'
68 validate_certs: false # only do this when you trust the network!
69
70 - name: Delete an alert profile from ManageIQ
71 community.general.manageiq_alert_profiles:
72 state: absent
73 name: Test profile
74 manageiq_connection:
75 url: 'http://127.0.0.1:3000'
76 username: 'admin'
77 password: 'smartvm'
78 validate_certs: false # only do this when you trust the network!
79 """
80
81 RETURN = r"""
82 """
83
84 from ansible.module_utils.basic import AnsibleModule
85
86 from ansible_collections.community.general.plugins.module_utils._manageiq import ManageIQ, manageiq_argument_spec
87
88
89 class ManageIQAlertProfiles:
90 """Object to execute alert profile management operations in manageiq."""
91
92 def __init__(self, manageiq):
93 self.manageiq = manageiq
94
95 self.module = self.manageiq.module
96 self.api_url = self.manageiq.api_url
97 self.client = self.manageiq.client
98 self.url = f"{self.api_url}/alert_definition_profiles"
99
100 def get_profiles(self):
101 """Get all alert profiles from ManageIQ"""
102 try:
103 response = self.client.get(f"{self.url}?expand=alert_definitions,resources")
104 except Exception as e:
105 self.module.fail_json(msg=f"Failed to query alert profiles: {e}")
106 return response.get("resources") or []
107
108 def get_alerts(self, alert_descriptions):
109 """Get a list of alert hrefs from a list of alert descriptions"""
110 alerts = []
111 for alert_description in alert_descriptions:
112 alert = self.manageiq.find_collection_resource_or_fail("alert_definitions", description=alert_description)
113 alerts.append(alert["href"])
114
115 return alerts
116
117 def add_profile(self, profile):
118 """Add a new alert profile to ManageIQ"""
119 # find all alerts to add to the profile
120 # we do this first to fail early if one is missing.
121 alerts = self.get_alerts(profile["alerts"])
122
123 # build the profile dict to send to the server
124
125 profile_dict = dict(name=profile["name"], description=profile["name"], mode=profile["resource_type"])
126 if profile["notes"]:
127 profile_dict["set_data"] = dict(notes=profile["notes"])
128
129 # send it to the server
130 try:
131 result = self.client.post(self.url, resource=profile_dict, action="create")
132 except Exception as e:
133 self.module.fail_json(msg=f"Creating profile failed {e}")
134
135 # now that it has been created, we can assign the alerts
136 self.assign_or_unassign(result["results"][0], alerts, "assign")
137
138 msg = f"Profile {profile['name']} created successfully"
139 return dict(changed=True, msg=msg)
140
141 def delete_profile(self, profile):
142 """Delete an alert profile from ManageIQ"""
143 try:
144 self.client.post(profile["href"], action="delete")
145 except Exception as e:
146 self.module.fail_json(msg=f"Deleting profile failed: {e}")
147
148 msg = f"Successfully deleted profile {profile['name']}"
149 return dict(changed=True, msg=msg)
150
151 def get_alert_href(self, alert):
152 """Get an absolute href for an alert"""
153 return f"{self.api_url}/alert_definitions/{alert['id']}"
154
155 def assign_or_unassign(self, profile, resources, action):
156 """Assign or unassign alerts to profile, and validate the result."""
157 alerts = [dict(href=href) for href in resources]
158
159 subcollection_url = f"{profile['href']}/alert_definitions"
160 try:
161 result = self.client.post(subcollection_url, resources=alerts, action=action)
162 if len(result["results"]) != len(alerts):
163 msg = (
164 f"Failed to {action} alerts to profile '{profile['name']}', "
165 f"expected {len(alerts)} alerts to be {action}ed, "
166 f"but only {result['results']} were {action}ed"
167 )
168 self.module.fail_json(msg=msg)
169 except Exception as e:
170 msg = f"Failed to {action} alerts to profile '{profile['name']}': {e}"
171 self.module.fail_json(msg=msg)
172
173 return result["results"]
174
175 def update_profile(self, old_profile, desired_profile):
176 """Update alert profile in ManageIQ"""
177 changed = False
178 # we need to use client.get to query the alert definitions
179 old_profile = self.client.get(f"{old_profile['href']}?expand=alert_definitions")
180
181 # figure out which alerts we need to assign / unassign
182 # alerts listed by the user:
183 desired_alerts = set(self.get_alerts(desired_profile["alerts"]))
184
185 # alert which currently exist in the profile
186 if "alert_definitions" in old_profile:
187 # we use get_alert_href to have a direct href to the alert
188 existing_alerts = {self.get_alert_href(alert) for alert in old_profile["alert_definitions"]}
189 else:
190 # no alerts in this profile
191 existing_alerts = set()
192
193 to_add = list(desired_alerts - existing_alerts)
194 to_remove = list(existing_alerts - desired_alerts)
195
196 # assign / unassign the alerts, if needed
197
198 if to_remove:
199 self.assign_or_unassign(old_profile, to_remove, "unassign")
200 changed = True
201 if to_add:
202 self.assign_or_unassign(old_profile, to_add, "assign")
203 changed = True
204
205 # update other properties
206 profile_dict = dict()
207
208 if old_profile["mode"] != desired_profile["resource_type"]:
209 # mode needs to be updated
210 profile_dict["mode"] = desired_profile["resource_type"]
211
212 # check if notes need to be updated
213 old_notes = old_profile.get("set_data", {}).get("notes")
214
215 if desired_profile["notes"] != old_notes:
216 profile_dict["set_data"] = dict(notes=desired_profile["notes"])
217
218 if profile_dict:
219 # if we have any updated values
220 changed = True
221 try:
222 self.client.post(old_profile["href"], resource=profile_dict, action="edit")
223 except Exception as e:
224 msg = f"Updating profile '{old_profile['name']}' failed: {e}"
225 self.module.fail_json(msg=msg)
226
227 if changed:
228 msg = f"Profile {desired_profile['name']} updated successfully"
229 else:
230 msg = f"No update needed for profile {desired_profile['name']}"
231 return dict(changed=changed, msg=msg)
232
233
234 def main():
235 argument_spec = dict(
236 name=dict(type="str", required=True),
237 resource_type=dict(
238 type="str",
239 choices=[
240 "Vm",
241 "ContainerNode",
242 "MiqServer",
243 "Host",
244 "Storage",
245 "EmsCluster",
246 "ExtManagementSystem",
247 "MiddlewareServer",
248 ],
249 ),
250 alerts=dict(type="list", elements="str"),
251 notes=dict(type="str"),
252 state=dict(default="present", choices=["present", "absent"]),
253 )
254 # add the manageiq connection arguments to the arguments
255 argument_spec.update(manageiq_argument_spec())
256
257 module = AnsibleModule(argument_spec=argument_spec, required_if=[("state", "present", ["resource_type", "alerts"])])
258
259 state = module.params["state"]
260 name = module.params["name"]
261
262 manageiq = ManageIQ(module)
263 manageiq_alert_profiles = ManageIQAlertProfiles(manageiq)
264
265 existing_profile = manageiq.find_collection_resource_by("alert_definition_profiles", name=name)
266
267 # we need to add or update the alert profile
268 if state == "present":
269 if not existing_profile:
270 # a profile with this name doesn't exist yet, let's create it
271 res_args = manageiq_alert_profiles.add_profile(module.params)
272 else:
273 # a profile with this name exists, we might need to update it
274 res_args = manageiq_alert_profiles.update_profile(existing_profile, module.params)
275
276 # this alert profile should not exist
277 if state == "absent":
278 # if we have an alert profile with this name, delete it
279 if existing_profile:
280 res_args = manageiq_alert_profiles.delete_profile(existing_profile)
281 else:
282 # This alert profile does not exist in ManageIQ, and that's okay
283 msg = f"Alert profile '{name}' does not exist in ManageIQ"
284 res_args = dict(changed=False, msg=msg)
285
286 module.exit_json(**res_args)
287
288
289 if __name__ == "__main__":
290 main()