Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 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_webhooks_http_servers
22 removed_in: 3.0.0
23 why: Updated modules released with increased functionality
24 description:
25 - Configure and query information about webhooks within the Meraki cloud.
26 extends_documentation_fragment: cisco.meraki.meraki
27 module: meraki_webhook
28 notes:
29 - Some of the options are likely only used for developers within Meraki.
30 options:
31 name:
32 description:
33 - Name of webhook.
34 type: str
35 net_id:
36 description:
37 - ID of network which configuration is applied to.
38 type: str
39 net_name:
40 aliases:
41 - network
42 description:
43 - Name of network which configuration is applied to.
44 type: str
45 payload_template_id:
46 description:
47 - The ID of the payload template. Overrides payload_template_name if passed too.
48 type: str
49 payload_template_name:
50 description:
51 - The name of the payload template
52 type: str
53 shared_secret:
54 description:
55 - Secret password to use when accessing webhook.
56 type: str
57 state:
58 choices:
59 - absent
60 - present
61 - query
62 default: query
63 description:
64 - Specifies whether object should be queried, created/modified, or removed.
65 type: str
66 test:
67 choices:
68 - test
69 description:
70 - Indicates whether to test or query status.
71 type: str
72 test_id:
73 description:
74 - ID of webhook test query.
75 type: str
76 url:
77 description:
78 - URL to access when calling webhook.
79 type: str
80 webhook_id:
81 description:
82 - Unique ID of webhook.
83 type: str
84 short_description: Manage webhooks configured in the Meraki cloud
85 """
86
87 EXAMPLES = r"""
88 - name: Create webhook
89 meraki_webhook:
90 auth_key: abc123
91 state: present
92 org_name: YourOrg
93 net_name: YourNet
94 name: Test_Hook
95 url: https://webhook.url/
96 shared_secret: shhhdonttellanyone
97 payload_template_name: Slack (included)
98 delegate_to: localhost
99 - name: Query one webhook
100 meraki_webhook:
101 auth_key: abc123
102 state: query
103 org_name: YourOrg
104 net_name: YourNet
105 name: Test_Hook
106 delegate_to: localhost
107 - name: Query all webhooks
108 meraki_webhook:
109 auth_key: abc123
110 state: query
111 org_name: YourOrg
112 net_name: YourNet
113 delegate_to: localhost
114 - name: Delete webhook
115 meraki_webhook:
116 auth_key: abc123
117 state: absent
118 org_name: YourOrg
119 net_name: YourNet
120 name: Test_Hook
121 delegate_to: localhost
122 - name: Test webhook
123 meraki_webhook:
124 auth_key: abc123
125 state: present
126 org_name: YourOrg
127 net_name: YourNet
128 test: test
129 url: https://webhook.url/abc123
130 delegate_to: localhost
131 - name: Get webhook status
132 meraki_webhook:
133 auth_key: abc123
134 state: present
135 org_name: YourOrg
136 net_name: YourNet
137 test: status
138 test_id: abc123531234
139 delegate_to: localhost
140 """
141
142 RETURN = r"""
143 data:
144 description: List of administrators.
145 returned: success
146 type: complex
147 contains:
148 id:
149 description: Unique ID of webhook.
150 returned: success
151 type: str
152 sample: aHR0cHM6Ly93ZWJob22LnvpdGUvOGViNWI3NmYtYjE2Ny00Y2I4LTlmYzQtND32Mj3F5NzIaMjQ0
153 name:
154 description: Descriptive name of webhook.
155 returned: success
156 type: str
157 sample: Test_Hook
158 networkId:
159 description: ID of network containing webhook object.
160 returned: success
161 type: str
162 sample: N_12345
163 shared_secret:
164 description: Password for webhook.
165 returned: success
166 type: str
167 sample: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
168 url:
169 description: URL of webhook endpoint.
170 returned: success
171 type: str
172 sample: https://webhook.url/abc123
173 status:
174 description: Status of webhook test.
175 returned: success, when testing webhook
176 type: str
177 sample: enqueued
178 payloadTemplate:
179 description: The payload template used when posting data to the HTTP server.
180 returned: success
181 type: str
182 sample:
183 payloadTemplateId: wpt_00001
184 name: Meraki (included)
185 """
186
187 from ansible.module_utils.basic import AnsibleModule, json
188 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
189 MerakiModule,
190 meraki_argument_spec,
191 )
192
193
194 def get_webhook_id(name, webhooks):
195 for webhook in webhooks:
196 if name == webhook["name"]:
197 return webhook["id"]
198 return None
199
200
201 def get_all_webhooks(meraki, net_id):
202 path = meraki.construct_path("get_all", net_id=net_id)
203 response = meraki.request(path, method="GET")
204 if meraki.status == 200:
205 return response
206
207
208 def sanitize_no_log_values(meraki):
209 try:
210 meraki.result["diff"]["before"][
211 "shared_secret"
212 ] = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
213 except KeyError:
214 pass
215 try:
216 for i in meraki.result['data']:
217 i[
218 "shared_secret"
219 ] = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
220 except (KeyError, TypeError):
221 pass
222 try:
223 meraki.result["data"]["shared_secret"] = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
224 except (KeyError, TypeError):
225 pass
226
227
228 def get_webhook_payload_templates(meraki, net_id):
229 path = meraki.construct_path("get_payload_templates", net_id=net_id)
230 response = meraki.request(path, "GET")
231 if meraki.status != 200:
232 meraki.fail_json(msg="Unable to get webhook payload templates")
233 return response
234
235
236 def get_webhook_payload_template_id(meraki, templates, name):
237 for template in templates:
238 if template["name"] == name:
239 return template["payloadTemplateId"]
240 meraki.fail_json(msg="No payload template found with the name {0}".format(name))
241
242
243 def main():
244 # define the available arguments/parameters that a user can pass to
245 # the module
246
247 argument_spec = meraki_argument_spec()
248 argument_spec.update(
249 state=dict(type="str", choices=["absent", "present", "query"], default="query"),
250 net_name=dict(type="str", aliases=["network"]),
251 net_id=dict(type="str"),
252 name=dict(type="str"),
253 url=dict(type="str"),
254 shared_secret=dict(type="str", no_log=True),
255 webhook_id=dict(type="str"),
256 test=dict(type="str", choices=["test"]),
257 test_id=dict(type="str"),
258 payload_template_name=dict(type="str"),
259 payload_template_id=dict(type="str"),
260 )
261
262 # the AnsibleModule object will be our abstraction working with Ansible
263 # this includes instantiation, a couple of common attr would be the
264 # args/params passed to the execution, as well as if the module
265 # supports check mode
266 module = AnsibleModule(
267 argument_spec=argument_spec,
268 supports_check_mode=True,
269 )
270 meraki = MerakiModule(module, function="webhooks")
271
272 meraki.params["follow_redirects"] = "all"
273
274 query_url = {"webhooks": "/networks/{net_id}/webhooks/httpServers"}
275 query_one_url = {"webhooks": "/networks/{net_id}/webhooks/httpServers/{hookid}"}
276 create_url = {"webhooks": "/networks/{net_id}/webhooks/httpServers"}
277 update_url = {"webhooks": "/networks/{net_id}/webhooks/httpServers/{hookid}"}
278 delete_url = {"webhooks": "/networks/{net_id}/webhooks/httpServers/{hookid}"}
279 test_url = {"webhooks": "/networks/{net_id}/webhooks/webhookTests"}
280 test_status_url = {"webhooks": "/networks/{net_id}/webhooks/webhookTests/{testid}"}
281 query_payload_templates = {
282 "webhooks": "/networks/{net_id}/webhooks/payloadTemplates"
283 }
284 meraki.url_catalog["get_all"].update(query_url)
285 meraki.url_catalog["get_one"].update(query_one_url)
286 meraki.url_catalog["create"] = create_url
287 meraki.url_catalog["update"] = update_url
288 meraki.url_catalog["delete"] = delete_url
289 meraki.url_catalog["test"] = test_url
290 meraki.url_catalog["test_status"] = test_status_url
291 meraki.url_catalog["get_payload_templates"] = query_payload_templates
292
293 org_id = meraki.params["org_id"]
294 if org_id is None:
295 org_id = meraki.get_org_id(meraki.params["org_name"])
296
297 net_id = meraki.params["net_id"]
298 if net_id is None:
299 nets = meraki.get_nets(org_id=org_id)
300 net_id = meraki.get_net_id(net_name=meraki.params["net_name"], data=nets)
301
302 templates = get_webhook_payload_templates(meraki, net_id)
303 payload_template_id = meraki.params["payload_template_id"]
304 if (
305 payload_template_id is None
306 and meraki.params["payload_template_name"] is not None
307 ):
308 payload_template_id = get_webhook_payload_template_id(
309 meraki, templates, name=meraki.params["payload_template_name"]
310 )
311
312 webhook_id = meraki.params["webhook_id"]
313 webhooks = None
314 if webhook_id is None and meraki.params["name"]:
315 webhooks = get_all_webhooks(meraki, net_id)
316 webhook_id = get_webhook_id(meraki.params["name"], webhooks)
317
318 if meraki.params["state"] == "present" and meraki.params["test"] is None:
319 payload = {
320 "name": meraki.params["name"],
321 "url": meraki.params["url"],
322 }
323 if meraki.params["shared_secret"] is not None:
324 payload["sharedSecret"] = meraki.params["shared_secret"]
325 if payload_template_id is not None:
326 payload["payloadTemplate"] = {"payloadTemplateId": payload_template_id}
327
328 if meraki.params["state"] == "query":
329 if webhook_id is not None: # Query a single webhook
330 path = meraki.construct_path(
331 "get_one", net_id=net_id, custom={"hookid": webhook_id}
332 )
333 response = meraki.request(path, method="GET")
334 if meraki.status == 200:
335 meraki.result["data"] = response
336 sanitize_no_log_values(meraki)
337 meraki.exit_json(**meraki.result)
338 elif meraki.params["test_id"] is not None:
339 path = meraki.construct_path(
340 "test_status",
341 net_id=net_id,
342 custom={"testid": meraki.params["test_id"]},
343 )
344 response = meraki.request(path, method="GET")
345 if meraki.status == 200:
346 meraki.result["data"] = response
347 sanitize_no_log_values(meraki)
348 meraki.exit_json(**meraki.result)
349 else:
350 path = meraki.construct_path("get_all", net_id=net_id)
351 response = meraki.request(path, method="GET")
352 if meraki.status == 200:
353 meraki.result["data"] = response
354 # meraki.fail_json(msg=meraki.result)
355 sanitize_no_log_values(meraki)
356 meraki.exit_json(**meraki.result)
357 elif meraki.params["state"] == "present":
358 if meraki.params["test"] == "test":
359 payload = {"url": meraki.params["url"]}
360 path = meraki.construct_path("test", net_id=net_id)
361 response = meraki.request(path, method="POST", payload=json.dumps(payload))
362 if meraki.status == 201:
363 meraki.result["data"] = response
364 meraki.exit_json(**meraki.result)
365 if webhook_id is None: # New webhook needs to be created
366 if meraki.check_mode is True:
367 meraki.result["data"] = payload
368 meraki.result["data"]["networkId"] = net_id
369 meraki.result["changed"] = True
370 meraki.exit_json(**meraki.result)
371 path = meraki.construct_path("create", net_id=net_id)
372 response = meraki.request(path, method="POST", payload=json.dumps(payload))
373 if meraki.status == 201:
374 meraki.result["data"] = response
375 meraki.result["changed"] = True
376 else: # Need to update
377 path = meraki.construct_path(
378 "get_one", net_id=net_id, custom={"hookid": webhook_id}
379 )
380 original = meraki.request(path, method="GET")
381 if meraki.is_update_required(original, payload):
382 if meraki.check_mode is True:
383 meraki.generate_diff(original, payload)
384 sanitize_no_log_values(meraki)
385 original.update(payload)
386 meraki.result["data"] = original
387 meraki.result["changed"] = True
388 meraki.exit_json(**meraki.result)
389 path = meraki.construct_path(
390 "update", net_id=net_id, custom={"hookid": webhook_id}
391 )
392 response = meraki.request(
393 path, method="PUT", payload=json.dumps(payload)
394 )
395 if meraki.status == 200:
396 # Not all fields are included so it needs to be checked to avoid comparing same thing
397 if meraki.is_update_required(original, response):
398 meraki.generate_diff(original, response)
399 sanitize_no_log_values(meraki)
400 meraki.result["data"] = response
401 meraki.result["changed"] = True
402 else:
403 meraki.result["data"] = original
404 elif meraki.params["state"] == "absent":
405 if webhook_id is None: # Make sure it is downloaded
406 if webhooks is None:
407 webhooks = get_all_webhooks(meraki, net_id)
408 webhook_id = get_webhook_id(meraki.params["name"], webhooks)
409 if webhook_id is None:
410 meraki.fail_json(
411 msg="There is no webhook with the name {0}".format(
412 meraki.params["name"]
413 )
414 )
415 if webhook_id: # Test to see if it exists
416 if meraki.module.check_mode is True:
417 meraki.result["data"] = None
418 meraki.result["changed"] = True
419 meraki.exit_json(**meraki.result)
420 path = meraki.construct_path(
421 "delete", net_id=net_id, custom={"hookid": webhook_id}
422 )
423 response = meraki.request(path, method="DELETE")
424 if meraki.status == 204:
425 meraki.result["data"] = response
426 meraki.result["changed"] = True
427
428 # in the event of a successful module execution, you will want to
429 # simple AnsibleModule.exit_json(), passing the key/value results
430 meraki.exit_json(**meraki.result)
431
432
433 if __name__ == "__main__":
434 main()