Debian Codegraph @

ansible_collections/cisco/meraki/plugins/action/organizations_login_security.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 enforcePasswordExpiration=dict(type="bool"),
35 passwordExpirationDays=dict(type="int"),
36 enforceDifferentPasswords=dict(type="bool"),
37 numDifferentPasswords=dict(type="int"),
38 enforceStrongPasswords=dict(type="bool"),
39 minimumPasswordLength=dict(type="int"),
40 enforceAccountLockout=dict(type="bool"),
41 accountLockoutAttempts=dict(type="int"),
42 enforceIdleTimeout=dict(type="bool"),
43 idleTimeoutMinutes=dict(type="int"),
44 enforceTwoFactorAuth=dict(type="bool"),
45 enforceLoginIpRanges=dict(type="bool"),
46 loginIpRanges=dict(type="list"),
47 apiAuthentication=dict(type="dict"),
48 organizationId=dict(type="str"),
49 ))
50
51 required_if = [
52 ("state", "present", ["organizationId"], True),
53 ]
54 required_one_of = []
55 mutually_exclusive = []
56 required_together = []
57
58
59 class OrganizationsLoginSecurity(object):
60 def __init__(self, params, meraki):
61 self.meraki = meraki
62 self.new_object = dict(
63 enforcePasswordExpiration=params.get("enforcePasswordExpiration"),
64 passwordExpirationDays=params.get("passwordExpirationDays"),
65 enforceDifferentPasswords=params.get("enforceDifferentPasswords"),
66 numDifferentPasswords=params.get("numDifferentPasswords"),
67 enforceStrongPasswords=params.get("enforceStrongPasswords"),
68 minimumPasswordLength=params.get("minimumPasswordLength"),
69 enforceAccountLockout=params.get("enforceAccountLockout"),
70 accountLockoutAttempts=params.get("accountLockoutAttempts"),
71 enforceIdleTimeout=params.get("enforceIdleTimeout"),
72 idleTimeoutMinutes=params.get("idleTimeoutMinutes"),
73 enforceTwoFactorAuth=params.get("enforceTwoFactorAuth"),
74 enforceLoginIpRanges=params.get("enforceLoginIpRanges"),
75 loginIpRanges=params.get("loginIpRanges"),
76 apiAuthentication=params.get("apiAuthentication"),
77 organization_id=params.get("organizationId"),
78 )
79
80 def get_all_params(self, name=None, id=None):
81 new_object_params = {}
82 if self.new_object.get('organizationId') is not None or self.new_object.get(
83 'organization_id') is not None:
84 new_object_params['organizationId'] = self.new_object.get(
85 'organizationId') or self.new_object.get('organization_id')
86 return new_object_params
87
88 def update_all_params(self):
89 new_object_params = {}
90 if self.new_object.get('enforcePasswordExpiration') is not None or self.new_object.get(
91 'enforce_password_expiration') is not None:
92 new_object_params['enforcePasswordExpiration'] = self.new_object.get(
93 'enforcePasswordExpiration')
94 if self.new_object.get('passwordExpirationDays') is not None or self.new_object.get(
95 'password_expiration_days') is not None:
96 new_object_params['passwordExpirationDays'] = self.new_object.get(
97 'passwordExpirationDays') or self.new_object.get('password_expiration_days')
98 if self.new_object.get('enforceDifferentPasswords') is not None or self.new_object.get(
99 'enforce_different_passwords') is not None:
100 new_object_params['enforceDifferentPasswords'] = self.new_object.get(
101 'enforceDifferentPasswords')
102 if self.new_object.get('numDifferentPasswords') is not None or self.new_object.get(
103 'num_different_passwords') is not None:
104 new_object_params['numDifferentPasswords'] = self.new_object.get(
105 'numDifferentPasswords') or self.new_object.get('num_different_passwords')
106 if self.new_object.get('enforceStrongPasswords') is not None or self.new_object.get(
107 'enforce_strong_passwords') is not None:
108 new_object_params['enforceStrongPasswords'] = self.new_object.get(
109 'enforceStrongPasswords')
110 if self.new_object.get('minimumPasswordLength') is not None or self.new_object.get(
111 'minimum_password_length') is not None:
112 new_object_params['minimumPasswordLength'] = self.new_object.get(
113 'minimumPasswordLength') or self.new_object.get('minimum_password_length')
114 if self.new_object.get('enforceAccountLockout') is not None or self.new_object.get(
115 'enforce_account_lockout') is not None:
116 new_object_params['enforceAccountLockout'] = self.new_object.get(
117 'enforceAccountLockout')
118 if self.new_object.get('accountLockoutAttempts') is not None or self.new_object.get(
119 'account_lockout_attempts') is not None:
120 new_object_params['accountLockoutAttempts'] = self.new_object.get(
121 'accountLockoutAttempts') or self.new_object.get('account_lockout_attempts')
122 if self.new_object.get('enforceIdleTimeout') is not None or self.new_object.get(
123 'enforce_idle_timeout') is not None:
124 new_object_params['enforceIdleTimeout'] = self.new_object.get(
125 'enforceIdleTimeout')
126 if self.new_object.get('idleTimeoutMinutes') is not None or self.new_object.get(
127 'idle_timeout_minutes') is not None:
128 new_object_params['idleTimeoutMinutes'] = self.new_object.get(
129 'idleTimeoutMinutes') or self.new_object.get('idle_timeout_minutes')
130 if self.new_object.get('enforceTwoFactorAuth') is not None or self.new_object.get(
131 'enforce_two_factor_auth') is not None:
132 new_object_params['enforceTwoFactorAuth'] = self.new_object.get(
133 'enforceTwoFactorAuth')
134 if self.new_object.get('enforceLoginIpRanges') is not None or self.new_object.get(
135 'enforce_login_ip_ranges') is not None:
136 new_object_params['enforceLoginIpRanges'] = self.new_object.get(
137 'enforceLoginIpRanges')
138 if self.new_object.get('loginIpRanges') is not None or self.new_object.get(
139 'login_ip_ranges') is not None:
140 new_object_params['loginIpRanges'] = self.new_object.get(
141 'loginIpRanges') or self.new_object.get('login_ip_ranges')
142 if self.new_object.get('apiAuthentication') is not None or self.new_object.get(
143 'api_authentication') is not None:
144 new_object_params['apiAuthentication'] = self.new_object.get(
145 'apiAuthentication') or self.new_object.get('api_authentication')
146 if self.new_object.get('organizationId') is not None or self.new_object.get(
147 'organization_id') is not None:
148 new_object_params['organizationId'] = self.new_object.get(
149 'organizationId') or self.new_object.get('organization_id')
150 return new_object_params
151
152 def get_object_by_name(self, name):
153 result = None
154 # NOTE: Does not have a get by name method, using get all
155 try:
156 items = self.meraki.exec_meraki(
157 family="organizations",
158 function="getOrganizationLoginSecurity",
159 params=self.get_all_params(name=name),
160 )
161 if isinstance(items, dict):
162 if 'response' in items:
163 items = items.get('response')
164 result = get_dict_result(items, 'name', name)
165 if result is None:
166 result = items
167 except Exception as e:
168 print("Error: ", e)
169 result = None
170 return result
171
172 def get_object_by_id(self, id):
173 result = None
174 # NOTE: Does not have a get by id method or it is in another action
175 return result
176
177 def exists(self):
178 prev_obj = None
179 id_exists = False
180 name_exists = False
181 o_id = self.new_object.get("id")
182 name = self.new_object.get("name")
183 if o_id:
184 prev_obj = self.get_object_by_name(o_id)
185 id_exists = prev_obj is not None and isinstance(prev_obj, dict)
186 if not id_exists and name:
187 prev_obj = self.get_object_by_name(name)
188 name_exists = prev_obj is not None and isinstance(prev_obj, dict)
189 if name_exists:
190 _id = prev_obj.get("id")
191 if id_exists and name_exists and o_id != _id:
192 raise InconsistentParameters(
193 "The 'id' and 'name' params don't refer to the same object")
194 if _id:
195 self.new_object.update(dict(id=_id))
196 it_exists = prev_obj is not None and isinstance(prev_obj, dict)
197 return (it_exists, prev_obj)
198
199 def requires_update(self, current_obj):
200 requested_obj = self.new_object
201
202 obj_params = [
203 ("enforcePasswordExpiration", "enforcePasswordExpiration"),
204 ("enforceDifferentPasswords", "enforceDifferentPasswords"),
205 ("numDifferentPasswords", "numDifferentPasswords"),
206 ("enforceStrongPasswords", "enforceStrongPasswords"),
207 ("minimumPasswordLength", "minimumPasswordLength"),
208 ("enforceAccountLockout", "enforceAccountLockout"),
209 ("accountLockoutAttempts", "accountLockoutAttempts"),
210 ("enforceIdleTimeout", "enforceIdleTimeout"),
211 ("idleTimeoutMinutes", "idleTimeoutMinutes"),
212 ("enforceTwoFactorAuth", "enforceTwoFactorAuth"),
213 ("enforceLoginIpRanges", "enforceLoginIpRanges"),
214 ("loginIpRanges", "loginIpRanges"),
215 ("apiAuthentication", "apiAuthentication"),
216 ("organizationId", "organizationId"),
217 ]
218 # Method 1. Params present in request (Ansible) obj are the same as the current (ISE) params
219 # If any does not have eq params, it requires update
220 return any(
221 not meraki_compare_equality2(
222 current_obj.get(meraki_param),
223 requested_obj.get(ansible_param)) for (
224 meraki_param,
225 ansible_param) in obj_params)
226
227 def update(self):
228 id = self.new_object.get("id")
229 name = self.new_object.get("name")
230 result = None
231 result = self.meraki.exec_meraki(
232 family="organizations",
233 function="updateOrganizationLoginSecurity",
234 params=self.update_all_params(),
235 op_modifies=True,
236 )
237 return result
238
239
240 class ActionModule(ActionBase):
241 def __init__(self, *args, **kwargs):
242 if not ANSIBLE_UTILS_IS_INSTALLED:
243 raise AnsibleActionFail(
244 "ansible.utils is not installed. Execute 'ansible-galaxy collection install ansible.utils'")
245 super(ActionModule, self).__init__(*args, **kwargs)
246 self._supports_async = False
247 self._supports_check_mode = False
248 self._result = None
249
250 # Checks the supplied parameters against the argument spec for this module
251 def _check_argspec(self):
252 aav = AnsibleArgSpecValidator(
253 data=self._task.args,
254 schema=dict(argument_spec=argument_spec),
255 schema_format="argspec",
256 schema_conditionals=dict(
257 required_if=required_if,
258 required_one_of=required_one_of,
259 mutually_exclusive=mutually_exclusive,
260 required_together=required_together,
261 ),
262 name=self._task.action,
263 )
264 valid, errors, self._task.args = aav.validate()
265 if not valid:
266 raise AnsibleActionFail(errors)
267
268 def run(self, tmp=None, task_vars=None):
269 self._task.diff = False
270 self._result = super(ActionModule, self).run(tmp, task_vars)
271 self._result["changed"] = False
272 self._check_argspec()
273
274 meraki = MERAKI(self._task.args)
275 obj = OrganizationsLoginSecurity(self._task.args, meraki)
276
277 state = self._task.args.get("state")
278
279 response = None
280 if state == "present":
281 (obj_exists, prev_obj) = obj.exists()
282 if obj_exists:
283 if obj.requires_update(prev_obj):
284 response = obj.update()
285 meraki.object_updated()
286 else:
287 response = prev_obj
288 meraki.object_already_present()
289 else:
290 meraki.fail_json(
291 "Object does not exists, plugin only has update")
292
293 self._result.update(dict(meraki_response=response))
294 self._result.update(meraki.exit_json())
295 return self._result