Debian Codegraph @

ansible_collections/cisco/meraki/plugins/modules/meraki_admin.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 __metaclass__ = type
9
10 ANSIBLE_METADATA = {
11 'metadata_version': '1.1',
12 "status": ['deprecated'],
13 'supported_by': 'community'
14 }
15
16 DOCUMENTATION = r'''
17 ---
18 module: meraki_admin
19 short_description: Manage administrators in the Meraki cloud
20 version_added: '2.16.0'
21 description:
22 - Allows for creation, management, and visibility into administrators within Meraki.
23 deprecated:
24 removed_in: '3.0.0'
25 why: Updated modules released with increased functionality
26 alternative: cisco.meraki.organizations_admins
27 options:
28 name:
29 description:
30 - Name of the dashboard administrator.
31 - Required when creating a new administrator.
32 type: str
33 email:
34 description:
35 - Email address for the dashboard administrator.
36 - Email cannot be updated.
37 - Required when creating or editing an administrator.
38 type: str
39 org_access:
40 description:
41 - Privileges assigned to the administrator in the organization.
42 aliases: [ orgAccess ]
43 choices: [ full, none, read-only ]
44 type: str
45 tags:
46 description:
47 - Tags the administrator has privileges on.
48 - When creating a new administrator, C(org_name), C(network), or C(tags) must be specified.
49 - If C(none) is specified, C(network) or C(tags) must be specified.
50 type: list
51 elements: dict
52 suboptions:
53 tag:
54 description:
55 - Object tag which privileges should be assigned.
56 type: str
57 access:
58 description:
59 - The privilege of the dashboard administrator for the tag.
60 type: str
61 networks:
62 description:
63 - List of networks the administrator has privileges on.
64 - When creating a new administrator, C(org_name), C(network), or C(tags) must be specified.
65 type: list
66 elements: dict
67 suboptions:
68 id:
69 description:
70 - Network ID for which administrator should have privileges assigned.
71 type: str
72 network:
73 description:
74 - Network name for which administrator should have privileges assigned.
75 type: str
76 access:
77 description:
78 - The privilege of the dashboard administrator on the network.
79 - Valid options are C(full), C(read-only), or C(none).
80 type: str
81 state:
82 description:
83 - Create or modify, or delete an organization
84 - If C(state) is C(absent), name takes priority over email if both are specified.
85 choices: [ absent, present, query ]
86 required: true
87 type: str
88 org_name:
89 description:
90 - Name of organization.
91 - Used when C(name) should refer to another object.
92 - When creating a new administrator, C(org_name), C(network), or C(tags) must be specified.
93 aliases: ['organization']
94 type: str
95 author:
96 - Kevin Breit (@kbreit)
97 extends_documentation_fragment: cisco.meraki.meraki
98 '''
99
100 EXAMPLES = r'''
101 - name: Query information about all administrators associated to the organization
102 meraki_admin:
103 auth_key: abc12345
104 org_name: YourOrg
105 state: query
106 delegate_to: localhost
107
108 - name: Query information about a single administrator by name
109 meraki_admin:
110 auth_key: abc12345
111 org_id: 12345
112 state: query
113 name: Jane Doe
114
115 - name: Query information about a single administrator by email
116 meraki_admin:
117 auth_key: abc12345
118 org_name: YourOrg
119 state: query
120 email: [email protected]
121
122 - name: Create new administrator with organization access
123 meraki_admin:
124 auth_key: abc12345
125 org_name: YourOrg
126 state: present
127 name: Jane Doe
128 org_access: read-only
129 email: [email protected]
130
131 - name: Create new administrator with organization access
132 meraki_admin:
133 auth_key: abc12345
134 org_name: YourOrg
135 state: present
136 name: Jane Doe
137 org_access: read-only
138 email: [email protected]
139
140 - name: Create a new administrator with organization access
141 meraki_admin:
142 auth_key: abc12345
143 org_name: YourOrg
144 state: present
145 name: Jane Doe
146 org_access: read-only
147 email: [email protected]
148
149 - name: Revoke access to an organization for an administrator
150 meraki_admin:
151 auth_key: abc12345
152 org_name: YourOrg
153 state: absent
154 email: [email protected]
155
156 - name: Create a new administrator with full access to two tags
157 meraki_admin:
158 auth_key: abc12345
159 org_name: YourOrg
160 state: present
161 name: Jane Doe
162 orgAccess: read-only
163 email: [email protected]
164 tags:
165 - tag: tenant
166 access: full
167 - tag: corporate
168 access: read-only
169
170 - name: Create a new administrator with full access to a network
171 meraki_admin:
172 auth_key: abc12345
173 org_name: YourOrg
174 state: present
175 name: Jane Doe
176 orgAccess: read-only
177 email: [email protected]
178 networks:
179 - id: N_12345
180 access: full
181 '''
182
183 RETURN = r'''
184 data:
185 description: List of administrators.
186 returned: success
187 type: complex
188 contains:
189 email:
190 description: Email address of administrator.
191 returned: success
192 type: str
193 sample: [email protected]
194 id:
195 description: Unique identification number of administrator.
196 returned: success
197 type: str
198 sample: 1234567890
199 name:
200 description: Given name of administrator.
201 returned: success
202 type: str
203 sample: John Doe
204 account_status:
205 description: Status of account.
206 returned: success
207 type: str
208 sample: ok
209 two_factor_auth_enabled:
210 description: Enabled state of two-factor authentication for administrator.
211 returned: success
212 type: bool
213 sample: false
214 has_api_key:
215 description: Defines whether administrator has an API assigned to their account.
216 returned: success
217 type: bool
218 sample: false
219 last_active:
220 description: Date and time of time the administrator was active within Dashboard.
221 returned: success
222 type: str
223 sample: 2019-01-28 14:58:56 -0800
224 networks:
225 description: List of networks administrator has access on.
226 returned: success
227 type: complex
228 contains:
229 id:
230 description: The network ID.
231 returned: when network permissions are set
232 type: str
233 sample: N_0123456789
234 access:
235 description: Access level of administrator. Options are 'full', 'read-only', or 'none'.
236 returned: when network permissions are set
237 type: str
238 sample: read-only
239 tags:
240 description: Tags the administrator has access on.
241 returned: success
242 type: complex
243 contains:
244 tag:
245 description: Tag name.
246 returned: when tag permissions are set
247 type: str
248 sample: production
249 access:
250 description: Access level of administrator. Options are 'full', 'read-only', or 'none'.
251 returned: when tag permissions are set
252 type: str
253 sample: full
254 org_access:
255 description: The privilege of the dashboard administrator on the organization. Options are 'full', 'read-only', or 'none'.
256 returned: success
257 type: str
258 sample: full
259
260 '''
261
262 import os
263 from ansible.module_utils.basic import AnsibleModule, json
264 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec
265
266
267 def get_admins(meraki, org_id):
268 admins = meraki.request(
269 meraki.construct_path(
270 'query',
271 function='admin',
272 org_id=org_id
273 ),
274 method='GET'
275 )
276 if meraki.status == 200:
277 return admins
278
279
280 def get_admin_id(meraki, data, name=None, email=None):
281 admin_id = None
282 for a in data:
283 if meraki.params['name'] is not None:
284 if meraki.params['name'] == a['name']:
285 if admin_id is not None:
286 meraki.fail_json(msg='There are multiple administrators with the same name')
287 else:
288 admin_id = a['id']
289 elif meraki.params['email']:
290 if meraki.params['email'] == a['email']:
291 return a['id']
292 if admin_id is None:
293 meraki.fail_json(msg='No admin_id found')
294 return admin_id
295
296
297 def get_admin(meraki, data, id):
298 for a in data:
299 if a['id'] == id:
300 return a
301 meraki.fail_json(msg='No admin found by specified name or email')
302
303
304 def find_admin(meraki, data, email):
305 for a in data:
306 if a['email'] == email:
307 return a
308 return None
309
310
311 def delete_admin(meraki, org_id, admin_id):
312 path = meraki.construct_path('revoke', 'admin', org_id=org_id) + admin_id
313 r = meraki.request(path,
314 method='DELETE'
315 )
316 if meraki.status == 204:
317 return r
318
319
320 def network_factory(meraki, networks, nets):
321 networks_new = []
322 for n in networks:
323 if 'network' in n and n['network'] is not None:
324 networks_new.append({'id': meraki.get_net_id(org_name=meraki.params['org_name'],
325 net_name=n['network'],
326 data=nets),
327 'access': n['access']
328 })
329 elif 'id' in n:
330 networks_new.append({'id': n['id'],
331 'access': n['access']
332 })
333
334 return networks_new
335
336
337 def create_admin(meraki, org_id, name, email):
338 payload = dict()
339 payload['name'] = name
340 payload['email'] = email
341
342 is_admin_existing = find_admin(meraki, get_admins(meraki, org_id), email)
343
344 if meraki.params['org_access'] is not None:
345 payload['orgAccess'] = meraki.params['org_access']
346 if meraki.params['tags'] is not None:
347 payload['tags'] = meraki.params['tags']
348 if meraki.params['networks'] is not None:
349 nets = meraki.get_nets(org_id=org_id)
350 networks = network_factory(meraki, meraki.params['networks'], nets)
351 payload['networks'] = networks
352 if is_admin_existing is None: # Create new admin
353 if meraki.module.check_mode is True:
354 meraki.result['data'] = payload
355 meraki.result['changed'] = True
356 meraki.exit_json(**meraki.result)
357 path = meraki.construct_path('create', function='admin', org_id=org_id)
358 r = meraki.request(path,
359 method='POST',
360 payload=json.dumps(payload)
361 )
362 if meraki.status == 201:
363 meraki.result['changed'] = True
364 return r
365 elif is_admin_existing is not None: # Update existing admin
366 if not meraki.params['tags']:
367 payload['tags'] = []
368 if not meraki.params['networks']:
369 payload['networks'] = []
370 if meraki.is_update_required(is_admin_existing, payload) is True:
371 if meraki.module.check_mode is True:
372 meraki.generate_diff(is_admin_existing, payload)
373 is_admin_existing.update(payload)
374 meraki.result['changed'] = True
375 meraki.result['data'] = payload
376 meraki.exit_json(**meraki.result)
377 path = meraki.construct_path('update', function='admin', org_id=org_id) + is_admin_existing['id']
378 r = meraki.request(path,
379 method='PUT',
380 payload=json.dumps(payload)
381 )
382 if meraki.status == 200:
383 meraki.result['changed'] = True
384 return r
385 else:
386 meraki.result['data'] = is_admin_existing
387 if meraki.module.check_mode is True:
388 meraki.result['data'] = payload
389 meraki.exit_json(**meraki.result)
390 return -1
391
392
393 def main():
394 # define the available arguments/parameters that a user can pass to
395 # the module
396
397 network_arg_spec = dict(id=dict(type='str'),
398 network=dict(type='str'),
399 access=dict(type='str'),
400 )
401
402 tag_arg_spec = dict(tag=dict(type='str'),
403 access=dict(type='str'),
404 )
405
406 argument_spec = meraki_argument_spec()
407 argument_spec.update(state=dict(type='str', choices=['present', 'query', 'absent'], required=True),
408 name=dict(type='str'),
409 email=dict(type='str'),
410 org_access=dict(type='str', aliases=['orgAccess'], choices=['full', 'read-only', 'none']),
411 tags=dict(type='list', elements='dict', options=tag_arg_spec),
412 networks=dict(type='list', elements='dict', options=network_arg_spec),
413 org_name=dict(type='str', aliases=['organization']),
414 org_id=dict(type='str'),
415 )
416
417 # the AnsibleModule object will be our abstraction working with Ansible
418 # this includes instantiation, a couple of common attr would be the
419 # args/params passed to the execution, as well as if the module
420 # supports check mode
421 module = AnsibleModule(argument_spec=argument_spec,
422 supports_check_mode=True,
423 )
424 meraki = MerakiModule(module, function='admin')
425
426 meraki.function = 'admin'
427 meraki.params['follow_redirects'] = 'all'
428
429 query_urls = {'admin': '/organizations/{org_id}/admins',
430 }
431 create_urls = {'admin': '/organizations/{org_id}/admins',
432 }
433 update_urls = {'admin': '/organizations/{org_id}/admins/',
434 }
435 revoke_urls = {'admin': '/organizations/{org_id}/admins/',
436 }
437
438 meraki.url_catalog['query'] = query_urls
439 meraki.url_catalog['create'] = create_urls
440 meraki.url_catalog['update'] = update_urls
441 meraki.url_catalog['revoke'] = revoke_urls
442
443 try:
444 meraki.params['auth_key'] = os.environ['MERAKI_KEY']
445 except KeyError:
446 pass
447
448 # if the user is working with this module in only check mode we do not
449 # want to make any changes to the environment, just return the current
450 # state with no modifications
451
452 # execute checks for argument completeness
453 if meraki.params['state'] == 'query':
454 meraki.mututally_exclusive = ['name', 'email']
455 if not meraki.params['org_name'] and not meraki.params['org_id']:
456 meraki.fail_json(msg='org_name or org_id required')
457 meraki.required_if = [(['state'], ['absent'], ['email']),
458 ]
459
460 # manipulate or modify the state as needed (this is going to be the
461 # part where your module will do what it needs to do)
462 org_id = meraki.params['org_id']
463 if not meraki.params['org_id']:
464 org_id = meraki.get_org_id(meraki.params['org_name'])
465 if meraki.params['state'] == 'query':
466 admins = get_admins(meraki, org_id)
467 if not meraki.params['name'] and not meraki.params['email']: # Return all admins for org
468 meraki.result['data'] = admins
469 if meraki.params['name'] is not None: # Return a single admin for org
470 admin_id = get_admin_id(meraki, admins, name=meraki.params['name'])
471 meraki.result['data'] = admin_id
472 admin = get_admin(meraki, admins, admin_id)
473 meraki.result['data'] = admin
474 elif meraki.params['email'] is not None:
475 admin_id = get_admin_id(meraki, admins, email=meraki.params['email'])
476 meraki.result['data'] = admin_id
477 admin = get_admin(meraki, admins, admin_id)
478 meraki.result['data'] = admin
479 elif meraki.params['state'] == 'present':
480 r = create_admin(meraki,
481 org_id,
482 meraki.params['name'],
483 meraki.params['email'],
484 )
485 if r != -1:
486 meraki.result['data'] = r
487 elif meraki.params['state'] == 'absent':
488 if meraki.module.check_mode is True:
489 meraki.result['data'] = {}
490 meraki.result['changed'] = True
491 meraki.exit_json(**meraki.result)
492 admin_id = get_admin_id(meraki,
493 get_admins(meraki, org_id),
494 email=meraki.params['email']
495 )
496 r = delete_admin(meraki, org_id, admin_id)
497
498 if r != -1:
499 meraki.result['data'] = r
500 meraki.result['changed'] = True
501
502 # in the event of a successful module execution, you will want to
503 # simple AnsibleModule.exit_json(), passing the key/value results
504 meraki.exit_json(**meraki.result)
505
506
507 if __name__ == '__main__':
508 main()