Debian Codegraph @

ansible_collections/cisco/meraki/plugins/action/networks_switch_stp.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2021, Cisco Systems
5 # GNU General Public License v3.0+ (see LICENSE or
6 # https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import (absolute_import, division, print_function)
9 __metaclass__ = type
10 from ansible.plugins.action import ActionBase
11 try:
12 from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import (
13 AnsibleArgSpecValidator, )
14 except ImportError:
15 ANSIBLE_UTILS_IS_INSTALLED = False
16 else:
17 ANSIBLE_UTILS_IS_INSTALLED = True
18 from ansible.errors import AnsibleActionFail
19 from ansible_collections.cisco.meraki.plugins.plugin_utils.meraki import (
20 MERAKI,
21 meraki_argument_spec,
22 meraki_compare_equality2,
23 get_dict_result,
24 )
25 from ansible_collections.cisco.meraki.plugins.plugin_utils.exceptions import (
26 InconsistentParameters,
27 )
28
29 # Get common arguments specification
30 argument_spec = meraki_argument_spec()
31 # Add arguments specific for this module
32 argument_spec.update(dict(
33 state=dict(type="str", default="present", choices=["present"]),
34 rstpEnabled=dict(type="bool"),
35 stpBridgePriority=dict(type="list"),
36 networkId=dict(type="str"),
37 ))
38
39 required_if = [
40 ("state", "present", ["networkId"], True),
41 ]
42 required_one_of = []
43 mutually_exclusive = []
44 required_together = []
45
46
47 class NetworksSwitchStp(object):
48 def __init__(self, params, meraki):
49 self.meraki = meraki
50 self.new_object = dict(
51 rstpEnabled=params.get("rstpEnabled"),
52 stpBridgePriority=params.get("stpBridgePriority"),
53 network_id=params.get("networkId"),
54 )
55
56 def get_all_params(self, name=None, id=None):
57 new_object_params = {}
58 if self.new_object.get('networkId') is not None or self.new_object.get(
59 'network_id') is not None:
60 new_object_params['networkId'] = self.new_object.get(
61 'networkId') or self.new_object.get('network_id')
62 return new_object_params
63
64 def update_all_params(self):
65 new_object_params = {}
66 if self.new_object.get('rstpEnabled') is not None or self.new_object.get(
67 'rstp_enabled') is not None:
68 new_object_params['rstpEnabled'] = self.new_object.get(
69 'rstpEnabled')
70 if self.new_object.get('stpBridgePriority') is not None or self.new_object.get(
71 'stp_bridge_priority') is not None:
72 new_object_params['stpBridgePriority'] = self.new_object.get(
73 'stpBridgePriority') or self.new_object.get('stp_bridge_priority')
74 if self.new_object.get('networkId') is not None or self.new_object.get(
75 'network_id') is not None:
76 new_object_params['networkId'] = self.new_object.get(
77 'networkId') or self.new_object.get('network_id')
78 return new_object_params
79
80 def get_object_by_name(self, name):
81 result = None
82 # NOTE: Does not have a get by name method, using get all
83 try:
84 items = self.meraki.exec_meraki(
85 family="switch",
86 function="getNetworkSwitchStp",
87 params=self.get_all_params(name=name),
88 )
89 if isinstance(items, dict):
90 if 'response' in items:
91 items = items.get('response')
92 result = get_dict_result(items, 'name', name)
93 if result is None:
94 result = items
95 except Exception as e:
96 print("Error: ", e)
97 result = None
98 return result
99
100 def get_object_by_id(self, id):
101 result = None
102 # NOTE: Does not have a get by id method or it is in another action
103 return result
104
105 def exists(self):
106 prev_obj = None
107 id_exists = False
108 name_exists = False
109 o_id = self.new_object.get(
110 "networkId") or self.new_object.get("network_id")
111 name = self.new_object.get("name")
112 if o_id:
113 prev_obj = self.get_object_by_name(o_id)
114 id_exists = prev_obj is not None and isinstance(prev_obj, dict)
115 if not id_exists and name:
116 prev_obj = self.get_object_by_name(name)
117 name_exists = prev_obj is not None and isinstance(prev_obj, dict)
118 if name_exists:
119 _id = prev_obj.get("id")
120 if id_exists and name_exists and o_id != _id:
121 raise InconsistentParameters(
122 "The 'id' and 'name' params don't refer to the same object")
123 if _id:
124 self.new_object.update(dict(id=_id))
125 it_exists = prev_obj is not None and isinstance(prev_obj, dict)
126 return (it_exists, prev_obj)
127
128 def requires_update(self, current_obj):
129 requested_obj = self.new_object
130
131 obj_params = [
132 ("rstpEnabled", "rstpEnabled"),
133 ("stpBridgePriority", "stpBridgePriority"),
134 ("networkId", "networkId"),
135 ]
136 # Method 1. Params present in request (Ansible) obj are the same as the current (ISE) params
137 # If any does not have eq params, it requires update
138 return any(
139 not meraki_compare_equality2(
140 current_obj.get(meraki_param),
141 requested_obj.get(ansible_param)) for (
142 meraki_param,
143 ansible_param) in obj_params)
144
145 def update(self):
146 id = self.new_object.get("id")
147 name = self.new_object.get("name")
148 result = None
149 result = self.meraki.exec_meraki(
150 family="switch",
151 function="updateNetworkSwitchStp",
152 params=self.update_all_params(),
153 op_modifies=True,
154 )
155 return result
156
157
158 class ActionModule(ActionBase):
159 def __init__(self, *args, **kwargs):
160 if not ANSIBLE_UTILS_IS_INSTALLED:
161 raise AnsibleActionFail(
162 "ansible.utils is not installed. Execute 'ansible-galaxy collection install ansible.utils'")
163 super(ActionModule, self).__init__(*args, **kwargs)
164 self._supports_async = False
165 self._supports_check_mode = False
166 self._result = None
167
168 # Checks the supplied parameters against the argument spec for this module
169 def _check_argspec(self):
170 aav = AnsibleArgSpecValidator(
171 data=self._task.args,
172 schema=dict(argument_spec=argument_spec),
173 schema_format="argspec",
174 schema_conditionals=dict(
175 required_if=required_if,
176 required_one_of=required_one_of,
177 mutually_exclusive=mutually_exclusive,
178 required_together=required_together,
179 ),
180 name=self._task.action,
181 )
182 valid, errors, self._task.args = aav.validate()
183 if not valid:
184 raise AnsibleActionFail(errors)
185
186 def run(self, tmp=None, task_vars=None):
187 self._task.diff = False
188 self._result = super(ActionModule, self).run(tmp, task_vars)
189 self._result["changed"] = False
190 self._check_argspec()
191
192 meraki = MERAKI(self._task.args)
193 obj = NetworksSwitchStp(self._task.args, meraki)
194
195 state = self._task.args.get("state")
196
197 response = None
198 if state == "present":
199 (obj_exists, prev_obj) = obj.exists()
200 if obj_exists:
201 if obj.requires_update(prev_obj):
202 response = obj.update()
203 meraki.object_updated()
204 else:
205 response = prev_obj
206 meraki.object_already_present()
207 else:
208 meraki.fail_json(
209 "Object does not exists, plugin only has update")
210
211 self._result.update(dict(meraki_response=response))
212 self._result.update(meraki.exit_json())
213 return self._result