Debian Codegraph @

ansible_collections/cisco/meraki/plugins/action/devices_switch_warm_spare.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 enabled=dict(type="bool"),
35 spareSerial=dict(type="str"),
36 serial=dict(type="str"),
37 ))
38
39 required_if = [
40 ("state", "present", ["serial"], True),
41 ]
42 required_one_of = []
43 mutually_exclusive = []
44 required_together = []
45
46
47 class DevicesSwitchWarmSpare(object):
48 def __init__(self, params, meraki):
49 self.meraki = meraki
50 self.new_object = dict(
51 enabled=params.get("enabled"),
52 spareSerial=params.get("spareSerial"),
53 serial=params.get("serial"),
54 )
55
56 def get_all_params(self, name=None, id=None):
57 new_object_params = {}
58 if self.new_object.get('serial') is not None or self.new_object.get(
59 'serial') is not None:
60 new_object_params['serial'] = self.new_object.get('serial')
61 return new_object_params
62
63 def update_all_params(self):
64 new_object_params = {}
65 if self.new_object.get('enabled') is not None or self.new_object.get(
66 'enabled') is not None:
67 new_object_params['enabled'] = self.new_object.get('enabled')
68 if self.new_object.get('spareSerial') is not None or self.new_object.get(
69 'spare_serial') is not None:
70 new_object_params['spareSerial'] = self.new_object.get(
71 'spareSerial') or self.new_object.get('spare_serial')
72 if self.new_object.get('serial') is not None or self.new_object.get(
73 'serial') is not None:
74 new_object_params['serial'] = self.new_object.get('serial') or \
75 self.new_object.get('serial')
76 return new_object_params
77
78 def get_object_by_name(self, name):
79 result = None
80 # NOTE: Does not have a get by name method, using get all
81 try:
82 items = self.meraki.exec_meraki(
83 family="switch",
84 function="getDeviceSwitchWarmSpare",
85 params=self.get_all_params(name=name),
86 )
87 if isinstance(items, dict):
88 if 'response' in items:
89 items = items.get('response')
90 result = get_dict_result(items, 'name', name)
91 if result is None:
92 result = items
93 except Exception as e:
94 print("Error: ", e)
95 result = None
96 return result
97
98 def get_object_by_id(self, id):
99 result = None
100 # NOTE: Does not have a get by id method or it is in another action
101 return result
102
103 def exists(self):
104 prev_obj = None
105 id_exists = False
106 name_exists = False
107 o_id = self.new_object.get("serial")
108 name = self.new_object.get("name")
109 if o_id:
110 prev_obj = self.get_object_by_name(o_id)
111 id_exists = prev_obj is not None and isinstance(prev_obj, dict)
112 if not id_exists and name:
113 prev_obj = self.get_object_by_name(name)
114 name_exists = prev_obj is not None and isinstance(prev_obj, dict)
115 if name_exists:
116 _id = prev_obj.get("id")
117 if id_exists and name_exists and o_id != _id:
118 raise InconsistentParameters(
119 "The 'id' and 'name' params don't refer to the same object")
120 if _id:
121 self.new_object.update(dict(id=_id))
122 it_exists = prev_obj is not None and isinstance(prev_obj, dict)
123 return (it_exists, prev_obj)
124
125 def requires_update(self, current_obj):
126 requested_obj = self.new_object
127
128 obj_params = [
129 ("enabled", "enabled"),
130 ("spareSerial", "spareSerial"),
131 ("serial", "serial"),
132 ]
133 # Method 1. Params present in request (Ansible) obj are the same as the current (ISE) params
134 # If any does not have eq params, it requires update
135 return any(
136 not meraki_compare_equality2(
137 current_obj.get(meraki_param),
138 requested_obj.get(ansible_param)) for (
139 meraki_param,
140 ansible_param) in obj_params)
141
142 def update(self):
143 id = self.new_object.get("id")
144 name = self.new_object.get("name")
145 result = None
146 result = self.meraki.exec_meraki(
147 family="switch",
148 function="updateDeviceSwitchWarmSpare",
149 params=self.update_all_params(),
150 op_modifies=True,
151 )
152 return result
153
154
155 class ActionModule(ActionBase):
156 def __init__(self, *args, **kwargs):
157 if not ANSIBLE_UTILS_IS_INSTALLED:
158 raise AnsibleActionFail(
159 "ansible.utils is not installed. Execute 'ansible-galaxy collection install ansible.utils'")
160 super(ActionModule, self).__init__(*args, **kwargs)
161 self._supports_async = False
162 self._supports_check_mode = False
163 self._result = None
164
165 # Checks the supplied parameters against the argument spec for this module
166 def _check_argspec(self):
167 aav = AnsibleArgSpecValidator(
168 data=self._task.args,
169 schema=dict(argument_spec=argument_spec),
170 schema_format="argspec",
171 schema_conditionals=dict(
172 required_if=required_if,
173 required_one_of=required_one_of,
174 mutually_exclusive=mutually_exclusive,
175 required_together=required_together,
176 ),
177 name=self._task.action,
178 )
179 valid, errors, self._task.args = aav.validate()
180 if not valid:
181 raise AnsibleActionFail(errors)
182
183 def run(self, tmp=None, task_vars=None):
184 self._task.diff = False
185 self._result = super(ActionModule, self).run(tmp, task_vars)
186 self._result["changed"] = False
187 self._check_argspec()
188
189 meraki = MERAKI(self._task.args)
190 obj = DevicesSwitchWarmSpare(self._task.args, meraki)
191
192 state = self._task.args.get("state")
193
194 response = None
195 if state == "present":
196 (obj_exists, prev_obj) = obj.exists()
197 if obj_exists:
198 if obj.requires_update(prev_obj):
199 response = obj.update()
200 meraki.object_updated()
201 else:
202 response = prev_obj
203 meraki.object_already_present()
204 else:
205 meraki.fail_json(
206 "Object does not exists, plugin only has update")
207
208 self._result.update(dict(meraki_response=response))
209 self._result.update(meraki.exit_json())
210 return self._result