Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, 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.devices_switch_ports
22 removed_in: 3.0.0
23 why: Updated modules released with increased functionality
24 description:
25 - Allows for management of switchports settings for Meraki MS switches.
26 extends_documentation_fragment: cisco.meraki.meraki
27 module: meraki_ms_switchport
28 options:
29 access_policy_number:
30 description:
31 - Number of the access policy to apply.
32 - Only applicable to access port types.
33 type: int
34 access_policy_type:
35 choices:
36 - Open
37 - Custom access policy
38 - MAC allow list
39 - Sticky MAC allow list
40 description:
41 - Type of access policy to apply to port.
42 type: str
43 allowed_vlans:
44 default: all
45 description:
46 - List of VLAN numbers to be allowed on switchport.
47 elements: str
48 type: list
49 enabled:
50 default: true
51 description:
52 - Whether a switchport should be enabled or disabled.
53 type: bool
54 flexible_stacking_enabled:
55 description:
56 - Whether flexible stacking capabilities are supported on the port.
57 type: bool
58 isolation_enabled:
59 default: false
60 description:
61 - Isolation status of switchport.
62 type: bool
63 link_negotiation:
64 choices:
65 - 1 Gigabit full duplex (auto)
66 - 1 Gigabit full duplex (forced)
67 - 10 Gigabit full duplex (auto)
68 - 10 Gigabit full duplex (forced)
69 - 100 Megabit (auto)
70 - 100 Megabit full duplex (forced)
71 - 2.5 Gigabit full duplex (auto)
72 - 2.5 Gigabit full duplex (forced)
73 - 5 Gigabit full duplex (auto)
74 - 5 Gigabit full duplex (forced)
75 - Auto negotiate
76 default: Auto negotiate
77 description:
78 - Link speed for the switchport.
79 type: str
80 mac_allow_list:
81 description:
82 - MAC addresses list that are allowed on a port.
83 - Only applicable to access port type.
84 - Only applicable to access_policy_type "MAC allow list".
85 suboptions:
86 macs:
87 description:
88 - List of MAC addresses to update with based on state option.
89 elements: str
90 type: list
91 state:
92 choices:
93 - merged
94 - replaced
95 - deleted
96 default: replaced
97 description:
98 - The state the configuration should be left in.
99 - Merged, MAC addresses provided will be added to the current allow list.
100 - Replaced, All MAC addresses are overwritten, only the MAC addresses provided
101 with exist in the allow list.
102 - Deleted, Remove the MAC addresses provided from the current allow list.
103 type: str
104 type: dict
105 name:
106 aliases:
107 - description
108 description:
109 - Switchport description.
110 type: str
111 number:
112 description:
113 - Port number.
114 type: str
115 poe_enabled:
116 default: true
117 description:
118 - Enable or disable Power Over Ethernet on a port.
119 type: bool
120 rstp_enabled:
121 default: true
122 description:
123 - Enable or disable Rapid Spanning Tree Protocol on a port.
124 type: bool
125 serial:
126 description:
127 - Serial nubmer of the switch.
128 required: true
129 type: str
130 state:
131 choices:
132 - query
133 - present
134 default: query
135 description:
136 - Specifies whether a switchport should be queried or modified.
137 type: str
138 sticky_mac_allow_list:
139 description:
140 - MAC addresses list that are allowed on a port.
141 - Only applicable to access port type.
142 - Only applicable to access_policy_type "Sticky MAC allow list".
143 suboptions:
144 macs:
145 description:
146 - List of MAC addresses to update with based on state option.
147 elements: str
148 type: list
149 state:
150 choices:
151 - merged
152 - replaced
153 - deleted
154 default: replaced
155 description:
156 - The state the configuration should be left in.
157 - Merged, MAC addresses provided will be added to the current allow list.
158 - Replaced, All MAC addresses are overwritten, only the MAC addresses provided
159 with exist in the allow list.
160 - Deleted, Remove the MAC addresses provided from the current allow list.
161 type: str
162 type: dict
163 sticky_mac_allow_list_limit:
164 description:
165 - The number of MAC addresses allowed in the sticky port allow list.
166 - Only applicable to access port type.
167 - Only applicable to access_policy_type "Sticky MAC allow list".
168 - The value must be equal to or greater then the list size of sticky_mac_allow_list.
169 Value will be checked for validity, during processing.
170 type: int
171 stp_guard:
172 choices:
173 - disabled
174 - root guard
175 - bpdu guard
176 - loop guard
177 default: disabled
178 description:
179 - Set state of STP guard.
180 type: str
181 tags:
182 description:
183 - List of tags to assign to a port.
184 elements: str
185 type: list
186 type:
187 choices:
188 - access
189 - trunk
190 default: access
191 description:
192 - Set port type.
193 type: str
194 vlan:
195 description:
196 - VLAN number assigned to port.
197 - If a port is of type trunk, the specified VLAN is the native VLAN.
198 - Setting value to 0 on a trunk will clear the VLAN.
199 type: int
200 voice_vlan:
201 description:
202 - VLAN number assigned to a port for voice traffic.
203 - Only applicable to access port type.
204 - Only applicable if voice_vlan_state is set to present.
205 type: int
206 voice_vlan_state:
207 choices:
208 - absent
209 - present
210 default: present
211 description:
212 - Specifies whether voice vlan configuration should be present or absent.
213 type: str
214 short_description: Manage switchports on a switch in the Meraki cloud
215 """
216
217 EXAMPLES = r"""
218 - name: Query information about all switchports on a switch
219 meraki_switchport:
220 auth_key: abc12345
221 state: query
222 serial: ABC-123
223 delegate_to: localhost
224 - name: Query information about all switchports on a switch
225 meraki_switchport:
226 auth_key: abc12345
227 state: query
228 serial: ABC-123
229 number: 2
230 delegate_to: localhost
231 - name: Name switchport
232 meraki_switchport:
233 auth_key: abc12345
234 state: present
235 serial: ABC-123
236 number: 7
237 name: Test Port
238 delegate_to: localhost
239 - name: Configure access port with voice VLAN
240 meraki_switchport:
241 auth_key: abc12345
242 state: present
243 serial: ABC-123
244 number: 7
245 enabled: true
246 name: Test Port
247 tags: desktop
248 type: access
249 vlan: 10
250 voice_vlan: 11
251 delegate_to: localhost
252 - name: Check access port for idempotency
253 meraki_switchport:
254 auth_key: abc12345
255 state: present
256 serial: ABC-123
257 number: 7
258 enabled: true
259 name: Test Port
260 tags: desktop
261 type: access
262 vlan: 10
263 voice_vlan: 11
264 delegate_to: localhost
265 - name: Configure trunk port with specific VLANs
266 meraki_switchport:
267 auth_key: abc12345
268 state: present
269 serial: ABC-123
270 number: 7
271 enabled: true
272 name: Server port
273 tags: server
274 type: trunk
275 allowed_vlans:
276 - 10
277 - 15
278 - 20
279 delegate_to: localhost
280 - name: Configure access port with sticky MAC allow list and limit.
281 meraki_switchport:
282 auth_key: abc12345
283 state: present
284 serial: ABC-123
285 number: 5
286 sticky_mac_allow_limit: 3
287 sticky_mac_allow_list:
288 macs:
289 - aa:aa:bb:bb:cc:cc
290 - bb:bb:aa:aa:cc:cc
291 - 11:aa:bb:bb:cc:cc
292 state: replaced
293 delegate_to: localhost
294 - name: Delete an existing MAC address from the sticky MAC allow list.
295 meraki_switchport:
296 auth_key: abc12345
297 state: present
298 serial: ABC-123
299 number: 5
300 sticky_mac_allow_list:
301 macs:
302 - aa:aa:bb:bb:cc:cc
303 state: deleted
304 delegate_to: localhost
305 - name: Add a MAC address to sticky MAC allow list.
306 meraki_switchport:
307 auth_key: abc12345
308 state: present
309 serial: ABC-123
310 number: 5
311 sticky_mac_allow_list:
312 macs:
313 - 22:22:bb:bb:cc:cc
314 state: merged
315 delegate_to: localhost
316 """
317
318 RETURN = r"""
319 data:
320 description: Information queried or updated switchports.
321 returned: success
322 type: complex
323 contains:
324 access_policy_type:
325 description: Type of access policy assigned to port
326 returned: success, when assigned
327 type: str
328 sample: "MAC allow list"
329 allowed_vlans:
330 description: List of VLANs allowed on an access port
331 returned: success, when port is set as access
332 type: str
333 sample: all
334 number:
335 description: Number of port.
336 returned: success
337 type: int
338 sample: 1
339 name:
340 description: Human friendly description of port.
341 returned: success
342 type: str
343 sample: "Jim Phone Port"
344 tags:
345 description: List of tags assigned to port.
346 returned: success
347 type: list
348 sample: ['phone', 'marketing']
349 enabled:
350 description: Enabled state of port.
351 returned: success
352 type: bool
353 sample: true
354 poe_enabled:
355 description: Power Over Ethernet enabled state of port.
356 returned: success
357 type: bool
358 sample: true
359 type:
360 description: Type of switchport.
361 returned: success
362 type: str
363 sample: trunk
364 vlan:
365 description: VLAN assigned to port.
366 returned: success
367 type: int
368 sample: 10
369 voice_vlan:
370 description: VLAN assigned to port with voice VLAN enabled devices.
371 returned: success
372 type: int
373 sample: 20
374 isolation_enabled:
375 description: Port isolation status of port.
376 returned: success
377 type: bool
378 sample: true
379 rstp_enabled:
380 description: Enabled or disabled state of Rapid Spanning Tree Protocol (RSTP)
381 returned: success
382 type: bool
383 sample: true
384 stp_guard:
385 description: State of STP guard
386 returned: success
387 type: str
388 sample: "Root Guard"
389 access_policy_number:
390 description: Number of assigned access policy. Only applicable to access ports.
391 returned: success
392 type: int
393 sample: 1234
394 link_negotiation:
395 description: Link speed for the port.
396 returned: success
397 type: str
398 sample: "Auto negotiate"
399 sticky_mac_allow_list_limit:
400 description: Number of MAC addresses allowed on a sticky port.
401 returned: success
402 type: int
403 sample: 6
404 sticky_mac_allow_list:
405 description: List of MAC addresses currently allowed on a sticky port. Used with access_policy_type of Sticky MAC allow list.
406 returned: success
407 type: list
408 sample: ["11:aa:bb:bb:cc:cc", "22:aa:bb:bb:cc:cc", "33:aa:bb:bb:cc:cc"]
409 mac_allow_list:
410 description: List of MAC addresses currently allowed on a non-sticky port. Used with access_policy_type of MAC allow list.
411 returned: success
412 type: list
413 sample: ["11:aa:bb:bb:cc:cc", "22:aa:bb:bb:cc:cc", "33:aa:bb:bb:cc:cc"]
414 port_schedule_id:
415 description: Unique ID of assigned port schedule
416 returned: success
417 type: str
418 sample: null
419 udld:
420 description: Alert state of UDLD
421 returned: success
422 type: str
423 sample: "Alert only"
424 flexible_stacking_enabled:
425 description: Whether flexible stacking capabilities are enabled on the port.
426 returned: success
427 type: bool
428 """
429
430 from ansible.module_utils.basic import AnsibleModule, json
431 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
432 MerakiModule,
433 meraki_argument_spec,
434 )
435
436 param_map = {
437 "access_policy_number": "accessPolicyNumber",
438 "access_policy_type": "accessPolicyType",
439 "allowed_vlans": "allowedVlans",
440 "enabled": "enabled",
441 "isolation_enabled": "isolationEnabled",
442 "link_negotiation": "linkNegotiation",
443 "name": "name",
444 "number": "number",
445 "poe_enabled": "poeEnabled",
446 "rstp_enabled": "rstpEnabled",
447 "stp_guard": "stpGuard",
448 "tags": "tags",
449 "type": "type",
450 "vlan": "vlan",
451 "voice_vlan": "voiceVlan",
452 "mac_allow_list": "macAllowList",
453 "sticky_mac_allow_list": "stickyMacAllowList",
454 "sticky_mac_allow_list_limit": "stickyMacAllowListLimit",
455 "adaptive_policy_group_id": "adaptivePolicyGroupId",
456 "peer_sgt_capable": "peerSgtCapable",
457 "flexible_stacking_enabled": "flexibleStackingEnabled",
458 }
459
460
461 def sort_vlans(meraki, vlans):
462 converted = set()
463 for vlan in vlans:
464 converted.add(int(vlan))
465 vlans_sorted = sorted(converted)
466 vlans_str = []
467 for vlan in vlans_sorted:
468 vlans_str.append(str(vlan))
469 return ",".join(vlans_str)
470
471
472 def assemble_payload(meraki):
473 payload = dict()
474 # if meraki.params['enabled'] is not None:
475 # payload['enabled'] = meraki.params['enabled']
476
477 for k, v in meraki.params.items():
478 try:
479 if meraki.params[k] is not None:
480 if k == "access_policy_number":
481 if meraki.params["access_policy_type"] is not None:
482 payload[param_map[k]] = v
483 else:
484 payload[param_map[k]] = v
485 except KeyError:
486 pass
487 return payload
488
489
490 def get_mac_list(original_allowed, new_mac_list, state):
491 if state == "deleted":
492 return [entry for entry in original_allowed if entry not in new_mac_list]
493 if state == "merged":
494 return original_allowed + list(set(new_mac_list) - set(original_allowed))
495 return new_mac_list
496
497
498 def clear_vlan(params, payload):
499 if params["vlan"] == 0:
500 payload["vlan"] = None
501 return payload
502
503
504 def main():
505 # define the available arguments/parameters that a user can pass to
506 # the module
507 argument_spec = meraki_argument_spec()
508
509 policy_data_arg_spec = dict(
510 macs=dict(type="list", elements="str"),
511 state=dict(
512 type="str", choices=["merged", "replaced", "deleted"], default="replaced"
513 ),
514 )
515
516 argument_spec.update(
517 state=dict(type="str", choices=["present", "query"], default="query"),
518 serial=dict(type="str", required=True),
519 number=dict(type="str"),
520 name=dict(type="str", aliases=["description"]),
521 tags=dict(type="list", elements="str"),
522 enabled=dict(type="bool", default=True),
523 type=dict(type="str", choices=["access", "trunk"], default="access"),
524 vlan=dict(type="int"),
525 voice_vlan=dict(type="int"),
526 voice_vlan_state=dict(
527 type="str", choices=["present", "absent"], default="present"
528 ),
529 allowed_vlans=dict(type="list", elements="str", default="all"),
530 poe_enabled=dict(type="bool", default=True),
531 isolation_enabled=dict(type="bool", default=False),
532 rstp_enabled=dict(type="bool", default=True),
533 stp_guard=dict(
534 type="str",
535 choices=["disabled", "root guard", "bpdu guard", "loop guard"],
536 default="disabled",
537 ),
538 access_policy_type=dict(
539 type="str",
540 choices=[
541 "Open",
542 "Custom access policy",
543 "MAC allow list",
544 "Sticky MAC allow list",
545 ],
546 ),
547 access_policy_number=dict(type="int"),
548 link_negotiation=dict(
549 type="str",
550 choices=[
551 "1 Gigabit full duplex (auto)",
552 "1 Gigabit full duplex (forced)",
553 "10 Gigabit full duplex (auto)",
554 "10 Gigabit full duplex (forced)",
555 "100 Megabit (auto)",
556 "100 Megabit full duplex (forced)",
557 "2.5 Gigabit full duplex (auto)",
558 "2.5 Gigabit full duplex (forced)",
559 "5 Gigabit full duplex (auto)",
560 "5 Gigabit full duplex (forced)",
561 "Auto negotiate",
562 ],
563 default="Auto negotiate",
564 ),
565 mac_allow_list=dict(type="dict", options=policy_data_arg_spec),
566 sticky_mac_allow_list=dict(type="dict", options=policy_data_arg_spec),
567 sticky_mac_allow_list_limit=dict(type="int"),
568 # adaptive_policy_group_id=dict(type=str),
569 # peer_sgt_capable=dict(type=bool),
570 flexible_stacking_enabled=dict(type="bool"),
571 )
572
573 # the AnsibleModule object will be our abstraction working with Ansible
574 # this includes instantiation, a couple of common attr would be the
575 # args/params passed to the execution, as well as if the module
576 # supports check mode
577 module = AnsibleModule(
578 argument_spec=argument_spec,
579 supports_check_mode=True,
580 )
581 meraki = MerakiModule(module, function="switchport")
582 if meraki.params.get("voice_vlan_state") == "absent" and meraki.params.get(
583 "voice_vlan"
584 ):
585 meraki.fail_json(
586 msg="voice_vlan_state cant be `absent` while voice_vlan is also defined."
587 )
588
589 meraki.params["follow_redirects"] = "all"
590
591 if meraki.params["type"] == "trunk":
592 if not meraki.params["allowed_vlans"]:
593 meraki.params["allowed_vlans"] = [
594 "all"
595 ] # Backdoor way to set default without conflicting on access
596
597 query_urls = {"switchport": "/devices/{serial}/switch/ports"}
598 query_url = {"switchport": "/devices/{serial}/switch/ports/{number}"}
599 update_url = {"switchport": "/devices/{serial}/switch/ports/{number}"}
600
601 meraki.url_catalog["get_all"].update(query_urls)
602 meraki.url_catalog["get_one"].update(query_url)
603 meraki.url_catalog["update"] = update_url
604
605 # execute checks for argument completeness
606
607 # manipulate or modify the state as needed (this is going to be the
608 # part where your module will do what it needs to do)
609 if meraki.params["state"] == "query":
610 if meraki.params["number"]:
611 path = meraki.construct_path(
612 "get_one",
613 custom={
614 "serial": meraki.params["serial"],
615 "number": meraki.params["number"],
616 },
617 )
618 response = meraki.request(path, method="GET")
619 meraki.result["data"] = response
620 else:
621 path = meraki.construct_path(
622 "get_all", custom={"serial": meraki.params["serial"]}
623 )
624 response = meraki.request(path, method="GET")
625 meraki.result["data"] = response
626 elif meraki.params["state"] == "present":
627 payload = assemble_payload(meraki)
628 # meraki.fail_json(msg='payload', payload=payload)
629 allowed = set() # Use a set to remove duplicate items
630 if meraki.params["allowed_vlans"][0] == "all":
631 allowed.add("all")
632 else:
633 for vlan in meraki.params["allowed_vlans"]:
634 allowed.add(str(vlan))
635 if meraki.params["vlan"] is not None:
636 allowed.add(str(meraki.params["vlan"]))
637 if len(allowed) > 1: # Convert from list to comma separated
638 payload["allowedVlans"] = sort_vlans(meraki, allowed)
639 else:
640 payload["allowedVlans"] = next(iter(allowed))
641
642 # Exceptions need to be made for idempotency check based on how Meraki returns
643 if meraki.params["type"] == "access":
644 if not meraki.params[
645 "vlan"
646 ]: # VLAN needs to be specified in access ports, but can't default to it
647 payload["vlan"] = 1
648 query_path = meraki.construct_path(
649 "get_one",
650 custom={
651 "serial": meraki.params["serial"],
652 "number": meraki.params["number"],
653 },
654 )
655 original = meraki.request(query_path, method="GET")
656 # Check voiceVlan to see if state is absent to remove the vlan.
657 if meraki.params.get("voice_vlan_state"):
658 if meraki.params.get("voice_vlan_state") == "absent":
659 payload["voiceVlan"] = None
660 else:
661 payload["voiceVlan"] = meraki.params.get("voice_vlan")
662 if meraki.params.get("mac_allow_list"):
663 macs = get_mac_list(
664 original.get("macAllowList"),
665 meraki.params["mac_allow_list"].get("macs"),
666 meraki.params["mac_allow_list"].get("state"),
667 )
668 payload["macAllowList"] = macs
669 # Evaluate Sticky Limit whether it was passed in or what is currently configured and was returned in GET call.
670 if meraki.params.get("sticky_mac_allow_list_limit"):
671 sticky_mac_limit = meraki.params.get("sticky_mac_allow_list_limit")
672 else:
673 sticky_mac_limit = original.get("stickyMacAllowListLimit")
674 if meraki.params.get("sticky_mac_allow_list"):
675 macs = get_mac_list(
676 original.get("stickyMacAllowList"),
677 meraki.params["sticky_mac_allow_list"].get("macs"),
678 meraki.params["sticky_mac_allow_list"].get("state"),
679 )
680 if int(sticky_mac_limit) < len(macs):
681 meraki.fail_json(
682 msg="Stick MAC Allow List Limit must be equal to or greater than length of Sticky MAC Allow List."
683 )
684 payload["stickyMacAllowList"] = macs
685 payload["stickyMacAllowListLimit"] = sticky_mac_limit
686 payload = clear_vlan(meraki.params, payload)
687 proposed = payload.copy()
688 if meraki.params["type"] == "trunk":
689 proposed["voiceVlan"] = original[
690 "voiceVlan"
691 ] # API shouldn't include voice VLAN on a trunk port
692 # meraki.fail_json(msg='Compare', original=original, payload=payload)
693 if meraki.is_update_required(original, proposed, optional_ignore=["number"]):
694 if meraki.check_mode is True:
695 original.update(proposed)
696 meraki.result["data"] = original
697 meraki.result["changed"] = True
698 meraki.exit_json(**meraki.result)
699 path = meraki.construct_path(
700 "update",
701 custom={
702 "serial": meraki.params["serial"],
703 "number": meraki.params["number"],
704 },
705 )
706 response = meraki.request(path, method="PUT", payload=json.dumps(payload))
707 meraki.result["data"] = response
708 meraki.result["changed"] = True
709 else:
710 meraki.result["data"] = original
711
712 # in the event of a successful module execution, you will want to
713 # simple AnsibleModule.exit_json(), passing the key/value results
714 meraki.exit_json(**meraki.result)
715
716
717 if __name__ == "__main__":
718 main()