Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, Tyler Christiansen (@supertylerc) <[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 - Tyler Christiansen (@supertylerc)
20 deprecated:
21 alternative: cisco.meraki.devices_wireless_radio_settings
22 removed_in: 3.0.0
23 why: Updated modules released with increased functionality
24 description:
25 - Allows for configuration of radio settings in Meraki MR wireless networks.
26 extends_documentation_fragment: cisco.meraki.meraki
27 module: meraki_mr_radio
28 options:
29 five_ghz_settings:
30 default: {}
31 description:
32 - Manual radio settings for 5 GHz.
33 suboptions:
34 channel:
35 choices:
36 - 36
37 - 40
38 - 44
39 - 48
40 - 52
41 - 56
42 - 60
43 - 64
44 - 100
45 - 104
46 - 108
47 - 112
48 - 116
49 - 120
50 - 124
51 - 128
52 - 132
53 - 136
54 - 140
55 - 144
56 - 149
57 - 153
58 - 157
59 - 161
60 - 165
61 description:
62 - Sets a manual channel for 5 GHz.
63 type: int
64 channel_width:
65 choices:
66 - auto
67 - '20'
68 - '40'
69 - '80'
70 description:
71 - Sets a manual channel for 5 GHz.
72 - Can be '0', '20', '40', or '80' or null for using auto channel width.
73 type: str
74 target_power:
75 description:
76 - Set a manual target power for 5 GHz.
77 - Can be between '8' or '30' or null for using auto power range.
78 type: int
79 type: dict
80 net_id:
81 description:
82 - ID of a network.
83 type: str
84 net_name:
85 aliases:
86 - network
87 description:
88 - Name of a network.
89 type: str
90 rf_profile_id:
91 description:
92 - The ID of an RF profile to assign to the device.
93 - If the value of this parameter is null, the appropriate basic RF profile (indoor
94 or outdoor) will be assigned to the device.
95 - Assigning an RF profile will clear ALL manually configured overrides on the
96 device (channel width, channel, power).
97 type: str
98 rf_profile_name:
99 description:
100 - The name of an RF profile to assign to the device.
101 - Similar to ``rf_profile_id``, but requires ``net_id`` (preferred) or ``net_name``.
102 type: str
103 serial:
104 description:
105 - Serial number of a device to query.
106 type: str
107 state:
108 choices:
109 - present
110 - query
111 default: present
112 description:
113 - Query or edit radio settings on a device.
114 type: str
115 two_four_ghz_settings:
116 default: {}
117 description:
118 - Manual radio settings for 2.4 GHz.
119 suboptions:
120 channel:
121 choices:
122 - 1
123 - 2
124 - 3
125 - 4
126 - 5
127 - 6
128 - 7
129 - 8
130 - 9
131 - 10
132 - 11
133 - 12
134 - 13
135 - 14
136 description:
137 - Sets a manual channel for 2.4 GHz.
138 - Can be '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12',
139 '13' or '14' or null for using auto channel.
140 type: int
141 target_power:
142 description:
143 - Set a manual target power for 2.4 GHz.
144 - Can be between '5' or '30' or null for using auto power range.
145 type: int
146 type: dict
147 short_description: Manage device radio settings for Meraki wireless networks
148 """
149
150 EXAMPLES = r"""
151 - name: Query a device's radio configuration
152 meraki_mr_radio:
153 auth_key: abc123
154 org_name: YourOrg
155 net_name: YourNet
156 serial: YourSerialNumber
157 state: query
158 delegate_to: localhost
159 - name: Configure a device's radios
160 meraki_mr_radio:
161 auth_key: abc123
162 org_name: YourOrg
163 net_name: YourNet
164 serial: YourSerialNumber
165 state: present
166 five_ghz_settings:
167 channel: 56
168 channel_width: 20
169 target_power: 10
170 two_four_ghz_settings:
171 channel: 6
172 target_power: 12
173 rf_profile_name: Test Profile
174 delegate_to: localhost
175 """
176
177 RETURN = r"""
178 data:
179 description: RF settings configured on a specific device.
180 returned: success
181 type: complex
182 contains:
183 serial:
184 description:
185 - Serial number of the device that was configured.
186 type: str
187 returned: success
188 sample: xyz
189 rf_profile_id:
190 description:
191 - The ID of an RF profile assigned to the device.
192 - Null indicates the appropriate basic RF profile (indoor or outdoor) is assigned to the device.
193 type: str
194 returned: success
195 sample: null
196 five_ghz_settings:
197 description:
198 - Configured manual radio settings for 5 GHz.
199 type: dict
200 returned: success
201 contains:
202 target_power:
203 description:
204 - Configured manual target power for 5 GHz.
205 - Null indicates auto power.
206 type: int
207 sample: 25
208 channel_width:
209 description:
210 - Configured manual channel for 5 GHz.
211 - Null indicates auto channel width.
212 type: str
213 sample: 40
214 channel:
215 description:
216 - Configured manual channel for 5 GHz.
217 - Null indicates auto channel.
218 type: str
219 sample: 56
220 two_four_ghz_settings:
221 description:
222 - Configured manual radio settings for 2.4 GHz.
223 type: dict
224 returned: success
225 contains:
226 target_power:
227 description:
228 - Configured manual target power for 2.4 GHz.
229 - Null indicates auto power.
230 type: int
231 sample: 15
232 channel:
233 description:
234 - Configured manual channel for 2.4 GHz.
235 - Null indicates auto channel.
236 type: str
237 sample: 11
238 """
239
240 from ansible.module_utils.basic import AnsibleModule, json
241 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
242 MerakiModule,
243 meraki_argument_spec,
244 )
245 from re import sub
246
247
248 def convert_to_camel_case(string):
249 """Convert "snake case" to "camel case"."""
250 string = sub(r"(_|-)+", " ", string).title().replace(" ", "")
251 return string[0].lower() + string[1:]
252
253
254 def _construct_payload(params):
255 """Recursively convert key names.
256
257 This function recursively updates all dict key names from the
258 Ansible/Python-style "snake case" to the format the Meraki API expects
259 ("camel case").
260 """
261 payload = {}
262 for k, v in params.items():
263 if isinstance(v, dict):
264 v = _construct_payload(v)
265 payload[convert_to_camel_case(k)] = v
266 return payload
267
268
269 def construct_payload(meraki):
270 """Construct API payload dict.
271
272 This function uses a ``valid_params`` variable to filter out keys from
273 ``meraki.params`` that aren't relevant to the Meraki API call.
274 """
275 params = {}
276 valid_params = [
277 "serial",
278 "rf_profile_id",
279 "five_ghz_settings",
280 "two_four_ghz_settings",
281 ]
282 for k, v in meraki.params.items():
283 if k not in valid_params:
284 continue
285 params[k] = v
286 return _construct_payload(params)
287
288
289 # Ansible spec for the 'five_ghz_settings' param, based on Meraki API.
290 FIVE_GHZ_SETTINGS_SPEC = {
291 "options": {
292 "target_power": {"type": "int"},
293 "channel_width": {"type": "str", "choices": ["auto", "20", "40", "80"]},
294 "channel": {
295 "type": "int",
296 "choices": [
297 36,
298 40,
299 44,
300 48,
301 52,
302 56,
303 60,
304 64,
305 100,
306 104,
307 108,
308 112,
309 116,
310 120,
311 124,
312 128,
313 132,
314 136,
315 140,
316 144,
317 149,
318 153,
319 157,
320 161,
321 165,
322 ],
323 },
324 },
325 "default": {},
326 }
327
328 # Ansible spec for the 'two_four_ghz_settings' param, based on Meraki API.
329 TWO_FOUR_GHZ_SETTINGS_SPEC = {
330 "options": {
331 "target_power": {"type": "int"},
332 "channel": {
333 "type": "int",
334 "choices": list(range(1, 15)),
335 },
336 },
337 "default": {},
338 }
339
340
341 def get_org_id(meraki):
342 """Get the Organization ID based on the Organization Name."""
343 org_id = meraki.params["org_id"]
344 if org_id is None:
345 org_id = meraki.get_org_id(meraki.params["org_name"])
346 return org_id
347
348
349 def get_net_id(meraki):
350 """Get the Network ID based on a Network Name."""
351 net_id = meraki.params["net_id"]
352 if net_id is None:
353 org_id = get_org_id(meraki)
354 nets = meraki.get_nets(org_id=org_id)
355 net_id = meraki.get_net_id(org_id, meraki.params["net_name"], data=nets)
356 return net_id
357
358
359 def get_rf_profile_id(meraki):
360 """Get the RF Profile ID for a given RF Profile Name."""
361 profile_id = meraki.params["rf_profile_id"]
362 profile_name = meraki.params["rf_profile_name"]
363 if profile_id is None and profile_name is not None:
364 net_id = get_net_id(meraki)
365 path = meraki.construct_path("get_all", "mr_rf_profile", net_id=net_id)
366 profiles = meraki.request(path, method="GET")
367 profile_id = next(
368 (
369 profile["id"]
370 for profile in profiles
371 if profile["name"] == meraki.params["rf_profile_name"]
372 ),
373 None,
374 )
375 return profile_id
376
377
378 def meraki_get_radio_settings(meraki):
379 """Query the Meraki API for the current radio settings."""
380 path = meraki.construct_path("get_one", custom={"serial": meraki.params["serial"]})
381 return meraki.request(path, method="GET")
382
383
384 def _meraki_run_query(meraki):
385 """Get the radio settings on the specified device."""
386 meraki.result["data"] = meraki_get_radio_settings(meraki)
387 meraki.exit_json(**meraki.result)
388
389
390 def _meraki_run_present(meraki):
391 """Update / check radio settings for a specified device."""
392 original = meraki_get_radio_settings(meraki)
393 meraki.result["data"] = original
394 meraki.params["rf_profile_id"] = get_rf_profile_id(meraki)
395 payload = construct_payload(meraki)
396 if meraki.is_update_required(original, payload) is True:
397 if meraki.check_mode is True:
398 meraki.result["data"] = payload
399 meraki.result["changed"] = True
400 meraki.result["original"] = original
401 else:
402 path = meraki.construct_path(
403 "update", custom={"serial": meraki.params["serial"]}
404 )
405 response = meraki.request(path, method="PUT", payload=json.dumps(payload))
406 meraki.result["data"] = response
407 meraki.result["changed"] = True
408 meraki.exit_json(**meraki.result)
409
410
411 def _meraki_run_func_lookup(state):
412 """Return the function that `meraki_run` will use based on `state`."""
413 return {
414 "query": _meraki_run_query,
415 "present": _meraki_run_present,
416 }[state]
417
418
419 def meraki_run(meraki):
420 """Perform API calls and generate responses based on the 'state' param."""
421 meraki_run_func = _meraki_run_func_lookup(meraki.params["state"])
422 meraki_run_func(meraki)
423
424
425 def update_url_catalog(meraki):
426 """Update the URL catalog available to the helper."""
427 query_urls = {"mr_radio": "/devices/{serial}/wireless/radio/settings"}
428 update_urls = {"mr_radio": "/devices/{serial}/wireless/radio/settings"}
429 query_all_urls = {"mr_rf_profile": "/networks/{net_id}/wireless/rfProfiles"}
430
431 meraki.url_catalog["get_one"].update(query_urls)
432 meraki.url_catalog["update"] = update_urls
433 meraki.url_catalog["get_all"].update(query_all_urls)
434
435
436 def validate_params(params):
437 """Validate parameters passed to this Ansible module.
438
439 When ``rf_profile_name`` is passed, we need to lookup the ID as that's what
440 the API expects. To look up the RF Profile ID, we need the network ID,
441 which might be derived based on the network name, in which case we need the
442 org ID or org name to complete the process.
443 """
444 valid = True
445 msg = None
446
447 if (
448 params["rf_profile_name"] is not None
449 and params["rf_profile_id"] is None
450 and params["net_id"] is None
451 ):
452 if params["net_name"] is None:
453 valid = False
454 msg = "When specifying 'rf_profile_name', either 'net_id' (preferred) or 'net_name' is required."
455 elif params["org_id"] is None and params["org_name"] is None:
456 valid = False
457 msg = "When specifying 'rf_profile_name' and omitting 'net_id', either 'org_id' (preferred) or 'org_name' is required."
458 return (valid, msg)
459
460
461 def main():
462 argument_spec = meraki_argument_spec()
463 argument_spec.update(
464 state=dict(type="str", choices=["present", "query"], default="present"),
465 org_name=dict(type="str", aliases=["organization"]),
466 org_id=dict(type="str"),
467 net_name=dict(type="str", aliases=["network"]),
468 net_id=dict(type="str"),
469 serial=dict(type="str"),
470 rf_profile_name=(dict(type="str")),
471 rf_profile_id=dict(type="str"),
472 five_ghz_settings=dict(
473 type="dict",
474 options=FIVE_GHZ_SETTINGS_SPEC["options"],
475 default=FIVE_GHZ_SETTINGS_SPEC["default"],
476 ),
477 two_four_ghz_settings=dict(
478 type="dict",
479 options=TWO_FOUR_GHZ_SETTINGS_SPEC["options"],
480 default=TWO_FOUR_GHZ_SETTINGS_SPEC["default"],
481 ),
482 )
483
484 module = AnsibleModule(
485 argument_spec=argument_spec,
486 supports_check_mode=True,
487 )
488 meraki = MerakiModule(module, function="mr_radio")
489 meraki.params["follow_redirects"] = "all"
490 valid_params, msg = validate_params(meraki.params)
491 if not valid_params:
492 meraki.fail_json(msg=msg)
493
494 update_url_catalog(meraki)
495 meraki_run(meraki)
496
497
498 if __name__ == "__main__":
499 main()