Debian Codegraph @

ansible_collections/cisco/meraki/plugins/modules/meraki_alert.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, 2019 Kevin Breit (@kbreit) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["deprecated"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 author:
19 - Kevin Breit (@kbreit)
20 deprecated:
21 alternative: cisco.meraki.networks_alerts_settings
22 removed_in: 3.0.0
23 why: Updated modules released with increased functionality
24 description:
25 - Allows for creation, management, and visibility into alert settings within Meraki.
26 extends_documentation_fragment: cisco.meraki.meraki
27 module: meraki_alert
28 options:
29 alerts:
30 description:
31 - Alert-specific configuration for each type.
32 elements: dict
33 suboptions:
34 alert_destinations:
35 description:
36 - A hash of destinations for this specific alert.
37 suboptions:
38 all_admins:
39 description:
40 - If true, all network admins will receive emails.
41 type: bool
42 emails:
43 description:
44 - A list of emails that will recieve the alert(s).
45 elements: str
46 type: list
47 http_server_ids:
48 description:
49 - A list of HTTP server IDs to send a Webhook to.
50 elements: str
51 type: list
52 snmp:
53 description:
54 - If true, then an SNMP trap will be sent if there is an SNMP trap server
55 configured for this network.
56 type: bool
57 type: dict
58 alert_type:
59 description:
60 - The type of alert.
61 type: str
62 enabled:
63 description:
64 - A boolean depicting if the alert is turned on or off.
65 type: bool
66 filters:
67 default: {}
68 description:
69 - A hash of specific configuration data for the alert. Only filters specific
70 to the alert will be updated.
71 - No validation checks occur against C(filters).
72 type: raw
73 type: list
74 default_destinations:
75 description:
76 - Properties for destinations when alert specific destinations aren't specified.
77 suboptions:
78 all_admins:
79 description:
80 - If true, all network admins will receive emails.
81 type: bool
82 emails:
83 description:
84 - A list of emails that will recieve the alert(s).
85 elements: str
86 type: list
87 http_server_ids:
88 description:
89 - A list of HTTP server IDs to send a Webhook to.
90 elements: str
91 type: list
92 snmp:
93 description:
94 - If true, then an SNMP trap will be sent if there is an SNMP trap server
95 configured for this network.
96 type: bool
97 type: dict
98 net_id:
99 description:
100 - ID number of a network.
101 type: str
102 net_name:
103 aliases:
104 - name
105 - network
106 description:
107 - Name of a network.
108 type: str
109 state:
110 choices:
111 - present
112 - query
113 default: present
114 description:
115 - Create or modify an alert.
116 type: str
117 short_description: Manage alerts in the Meraki cloud
118 version_added: 2.1.0
119 """
120
121 EXAMPLES = r"""
122 - name: Update settings
123 meraki_alert:
124 auth_key: abc123
125 org_name: YourOrg
126 net_name: YourNet
127 state: present
128 default_destinations:
129 emails:
130 - youremail@yourcorp
131 - youremail2@yourcorp
132 all_admins: true
133 snmp: false
134 alerts:
135 - alert_type: gatewayDown
136 enabled: true
137 filters:
138 timeout: 60
139 alert_destinations:
140 emails:
141 - youremail@yourcorp
142 - youremail2@yourcorp
143 all_admins: true
144 snmp: false
145 - alert_type: usageAlert
146 enabled: true
147 filters:
148 period: 1200
149 threshold: 104857600
150 alert_destinations:
151 emails:
152 - youremail@yourcorp
153 - youremail2@yourcorp
154 all_admins: true
155 snmp: false
156 - name: Query all settings
157 meraki_alert:
158 auth_key: abc123
159 org_name: YourOrg
160 net_name: YourNet
161 state: query
162 delegate_to: localhost
163 """
164
165 RETURN = r"""
166 data:
167 description: Information about the created or manipulated object.
168 returned: info
169 type: complex
170 contains:
171 default_destinations:
172 description: Properties for destinations when alert specific destinations aren't specified.
173 returned: success
174 type: complex
175 contains:
176 all_admins:
177 description: If true, all network admins will receive emails.
178 type: bool
179 sample: true
180 returned: success
181 snmp:
182 description: If true, then an SNMP trap will be sent if there is an SNMP trap server configured for this network.
183 type: bool
184 sample: true
185 returned: success
186 emails:
187 description: A list of emails that will recieve the alert(s).
188 type: list
189 returned: success
190 http_server_ids:
191 description: A list of HTTP server IDs to send a Webhook to.
192 type: list
193 returned: success
194 alerts:
195 description: Alert-specific configuration for each type.
196 type: complex
197 contains:
198 alert_type:
199 description: The type of alert.
200 type: str
201 returned: success
202 enabled:
203 description: A boolean depicting if the alert is turned on or off.
204 type: bool
205 returned: success
206 filters:
207 description:
208 - A hash of specific configuration data for the alert. Only filters specific to the alert will be updated.
209 - No validation checks occur against C(filters).
210 type: complex
211 returned: success
212 alert_destinations:
213 description: A hash of destinations for this specific alert.
214 type: complex
215 contains:
216 all_admins:
217 description: If true, all network admins will receive emails.
218 type: bool
219 returned: success
220 snmp:
221 description: If true, then an SNMP trap will be sent if there is an SNMP trap server configured for this network.
222 type: bool
223 returned: success
224 emails:
225 description: A list of emails that will recieve the alert(s).
226 type: list
227 returned: success
228 http_server_ids:
229 description: A list of HTTP server IDs to send a Webhook to.
230 type: list
231 returned: success
232 """
233
234 from ansible.module_utils.basic import AnsibleModule, json
235 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
236 MerakiModule,
237 meraki_argument_spec,
238 )
239
240
241 def get_alert_by_type(type, meraki):
242 for alert in meraki.params["alerts"]:
243 if alert["alert_type"] == type:
244 return alert
245 return None
246
247
248 def construct_payload(meraki, current):
249 payload = {}
250 if meraki.params["default_destinations"] is not None:
251 payload["defaultDestinations"] = {}
252 if meraki.params["default_destinations"]["all_admins"] is not None:
253 payload["defaultDestinations"]["allAdmins"] = meraki.params["default_destinations"]["all_admins"]
254 if meraki.params["default_destinations"]["snmp"] is not None:
255 payload["defaultDestinations"]["snmp"] = meraki.params["default_destinations"]["snmp"]
256 if meraki.params["default_destinations"]["emails"] is not None:
257 payload["defaultDestinations"]["emails"] = meraki.params["default_destinations"]["emails"]
258 if len(payload["defaultDestinations"]["emails"]) > 0 and payload["defaultDestinations"]["emails"][0] == "None":
259 # Ansible is setting the first item to be "None" so we need to clear this
260 # This happens when an empty list is provided to clear emails
261 del payload["defaultDestinations"]["emails"][0]
262 if meraki.params["default_destinations"]["http_server_ids"] is not None:
263 payload["defaultDestinations"]["httpServerIds"] = meraki.params["default_destinations"]["http_server_ids"]
264 if len(payload["defaultDestinations"]["httpServerIds"]) > 0 and payload["defaultDestinations"]["httpServerIds"][0] == "None":
265 # Ansible is setting the first item to be "None" so we need to clear this
266 # This happens when an empty list is provided to clear server IDs
267 del payload["defaultDestinations"]["httpServerIds"][0]
268 if meraki.params["alerts"] is not None:
269 payload["alerts"] = []
270 # All data should be resubmitted, otherwise it will clear the alert
271 # Also, the order matters so it should go in the same order as current
272 modified_types = [type["alert_type"] for type in meraki.params["alerts"]]
273
274 # for alert in meraki.params["alerts"]:
275 for current_alert in current["alerts"]:
276 if current_alert["type"] not in modified_types:
277 payload["alerts"].append(current_alert)
278 else:
279 alert = get_alert_by_type(current_alert["type"], meraki)
280 alert_temp = {"type": None}
281 if alert["alert_type"] is not None:
282 alert_temp["type"] = alert["alert_type"]
283 if alert["enabled"] is not None:
284 alert_temp["enabled"] = alert["enabled"]
285 if alert["filters"] is not None:
286 alert_temp["filters"] = alert["filters"]
287 if alert["alert_destinations"] is not None:
288 alert_temp["alertDestinations"] = dict()
289 if alert["alert_destinations"]["all_admins"] is not None:
290 alert_temp["alertDestinations"]["allAdmins"] = alert["alert_destinations"]["all_admins"]
291 if alert["alert_destinations"]["snmp"] is not None:
292 alert_temp["alertDestinations"]["snmp"] = alert["alert_destinations"]["snmp"]
293 if alert["alert_destinations"]["emails"] is not None:
294 alert_temp["alertDestinations"]["emails"] = alert["alert_destinations"]["emails"]
295 if len(alert_temp["alertDestinations"]["emails"]) > 0 and alert_temp["alertDestinations"]["emails"][0] == "None":
296 # Ansible is setting the first item to be "None" so we need to clear this
297 # This happens when an empty list is provided to clear emails
298 del alert_temp["defaultDestinations"]["emails"][0]
299 if alert["alert_destinations"]["http_server_ids"] is not None:
300 alert_temp["alertDestinations"]["httpServerIds"] = alert["alert_destinations"]["http_server_ids"]
301 if len(alert_temp["alertDestinations"]["httpServerIds"]) > 0 and alert_temp["alertDestinations"]["httpServerIds"][0] == "None":
302 # Ansible is setting the first item to be "None" so we need to clear this
303 # This happens when an empty list is provided to clear server IDs
304 del alert_temp["defaultDestinations"]["httpServerIds"][0]
305 payload["alerts"].append(alert_temp)
306 return payload
307
308
309 def main():
310
311 # define the available arguments/parameters that a user can pass to
312 # the module
313
314 destinations_arg_spec = dict(
315 all_admins=dict(type="bool"),
316 snmp=dict(type="bool"),
317 emails=dict(type="list", elements="str"),
318 http_server_ids=dict(type="list", elements="str"),
319 )
320
321 alerts_arg_spec = dict(
322 alert_type=dict(type="str"),
323 enabled=dict(type="bool"),
324 alert_destinations=dict(
325 type="dict", default=None, options=destinations_arg_spec
326 ),
327 filters=dict(type="raw", default={}),
328 )
329
330 argument_spec = meraki_argument_spec()
331 argument_spec.update(
332 net_id=dict(type="str"),
333 net_name=dict(type="str", aliases=["name", "network"]),
334 state=dict(type="str", choices=["present", "query"], default="present"),
335 default_destinations=dict(
336 type="dict", default=None, options=destinations_arg_spec
337 ),
338 alerts=dict(type="list", elements="dict", options=alerts_arg_spec),
339 )
340
341 # the AnsibleModule object will be our abstraction working with Ansible
342 # this includes instantiation, a couple of common attr would be the
343 # args/params passed to the execution, as well as if the module
344 # supports check mode
345 module = AnsibleModule(
346 argument_spec=argument_spec,
347 supports_check_mode=True,
348 )
349
350 meraki = MerakiModule(module, function="alert")
351 module.params["follow_redirects"] = "all"
352
353 query_urls = {"alert": "/networks/{net_id}/alerts/settings"}
354 update_urls = {"alert": "/networks/{net_id}/alerts/settings"}
355 meraki.url_catalog["get_all"].update(query_urls)
356 meraki.url_catalog["update"] = update_urls
357
358 # manipulate or modify the state as needed (this is going to be the
359 # part where your module will do what it needs to do)
360
361 org_id = meraki.params["org_id"]
362 if org_id is None:
363 org_id = meraki.get_org_id(meraki.params["org_name"])
364 net_id = meraki.params["net_id"]
365 if net_id is None:
366 nets = meraki.get_nets(org_id=org_id)
367 net_id = meraki.get_net_id(net_name=meraki.params["net_name"], data=nets)
368
369 if meraki.params["state"] == "query":
370 path = meraki.construct_path("get_all", net_id=net_id)
371 response = meraki.request(path, method="GET")
372 if meraki.status == 200:
373 meraki.result["data"] = response
374 meraki.exit_json(**meraki.result)
375 elif meraki.params["state"] == "present":
376 path = meraki.construct_path("get_all", net_id=net_id)
377 original = meraki.request(path, method="GET")
378 payload = construct_payload(meraki, original)
379 if meraki.is_update_required(original, payload):
380 if meraki.check_mode is True:
381 meraki.generate_diff(original, payload)
382 meraki.result["data"] = payload
383 meraki.result["changed"] = True
384 meraki.exit_json(**meraki.result)
385 path = meraki.construct_path("update", net_id=net_id)
386 response = meraki.request(path, method="PUT", payload=json.dumps(payload))
387 if meraki.status == 200:
388 meraki.generate_diff(original, payload)
389 meraki.result["data"] = response
390 meraki.result["changed"] = True
391 meraki.exit_json(**meraki.result)
392 else:
393 meraki.result["data"] = original
394 meraki.exit_json(**meraki.result)
395
396 # in the event of a successful module execution, you will want to
397 # simple AnsibleModule.exit_json(), passing the key/value results
398 meraki.exit_json(**meraki.result)
399
400
401 if __name__ == "__main__":
402 main()