Debian Codegraph @

ansible_collections/cisco/iosxr/plugins/modules/iosxr_user.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2017, Ansible by Red Hat, inc
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
10 __metaclass__ = type
11
12
13 DOCUMENTATION = """
14 module: iosxr_user
15 author:
16 - Trishna Guha (@trishnaguha)
17 - Sebastiaan van Doesselaar (@sebasdoes)
18 - Kedar Kekan (@kedarX)
19 short_description: Module to manage the aggregates of local users.
20 description:
21 - This module provides declarative management of the local usernames configured on
22 network devices. It allows playbooks to manage either individual usernames or the
23 aggregate of usernames in the current running config. It also supports purging usernames
24 from the configuration that are not explicitly defined.
25 version_added: 1.0.0
26 extends_documentation_fragment:
27 - cisco.iosxr.iosxr
28 notes:
29 - This module works with connection C(network_cli) and C(netconf). See L(the IOS-XR
30 Platform Options,../network/user_guide/platform_iosxr.html).
31 options:
32 aggregate:
33 description:
34 - The set of username objects to be configured on the remote Cisco IOS XR device.
35 The list entries can either be the username or a hash of username and properties.
36 This argument is mutually exclusive with the C(name) argument.
37 aliases:
38 - users
39 - collection
40 type: list
41 elements: dict
42 suboptions:
43 name:
44 description:
45 - The username to be configured on the Cisco IOS XR device. This argument accepts
46 a string value and is mutually exclusive with the C(aggregate) argument. Please
47 note that this option is not same as C(provider username).
48 type: str
49 required: true
50 configured_password:
51 description:
52 - The password to be configured on the Cisco IOS XR device. The password needs
53 to be provided in clear text. Password is encrypted on the device when used
54 with I(cli) and by Ansible when used with I(netconf) using the same MD5 hash
55 technique with salt size of 3. Please note that this option is not same as C(provider
56 password).
57 type: str
58 update_password:
59 description:
60 - Since passwords are encrypted in the device running config, this argument will
61 instruct the module when to change the password. When set to C(always), the
62 password will always be updated in the device and when set to C(on_create) the
63 password will be updated only if the username is created.
64 type: str
65 choices:
66 - on_create
67 - always
68 group:
69 description:
70 - Configures the group for the username in the device running configuration. The
71 argument accepts a string value defining the group name. This argument does
72 not check if the group has been configured on the device.
73 type: str
74 aliases:
75 - role
76 groups:
77 description:
78 - Configures the groups for the username in the device running configuration.
79 The argument accepts a list of group names. This argument does not check if
80 the group has been configured on the device. It is similar to the aggregate
81 command for usernames, but lets you configure multiple groups for the user(s).
82 type: list
83 elements: str
84 admin:
85 description:
86 - Enters into administration configuration mode for making config changes to the
87 device.
88 - Applicable only when using network_cli transport
89 type: bool
90 state:
91 description:
92 - Configures the state of the username definition as it relates to the device
93 operational configuration. When set to I(present), the username(s) should be
94 configured in the device active configuration and when set to I(absent) the
95 username(s) should not be in the device active configuration
96 type: str
97 choices:
98 - present
99 - absent
100 public_key:
101 description:
102 - Configures the contents of the public keyfile to upload to the IOS-XR node.
103 This enables users to login using the accompanying private key. IOS-XR only
104 accepts base64 decoded files, so this will be decoded and uploaded to the node.
105 Do note that this requires an OpenSSL public key file, PuTTy generated files
106 will not work! Mutually exclusive with public_key_contents. If used with multiple
107 users in aggregates, then the same key file is used for all users.
108 type: str
109 public_key_contents:
110 description:
111 - Configures the contents of the public keyfile to upload to the IOS-XR node.
112 This enables users to login using the accompanying private key. IOS-XR only
113 accepts base64 decoded files, so this will be decoded and uploaded to the node.
114 Do note that this requires an OpenSSL public key file, PuTTy generated files
115 will not work! Mutually exclusive with public_key.If used with multiple users
116 in aggregates, then the same key file is used for all users.
117 type: str
118 name:
119 description:
120 - The username to be configured on the Cisco IOS XR device. This argument accepts
121 a string value and is mutually exclusive with the C(aggregate) argument. Please
122 note that this option is not same as C(provider username).
123 type: str
124 configured_password:
125 description:
126 - The password to be configured on the Cisco IOS XR device. The password needs
127 to be provided in clear text. Password is encrypted on the device when used
128 with I(cli) and by Ansible when used with I(netconf) using the same MD5 hash
129 technique with salt size of 3. Please note that this option is not same as C(provider
130 password).
131 type: str
132 update_password:
133 description:
134 - Since passwords are encrypted in the device running config, this argument will
135 instruct the module when to change the password. When set to C(always), the
136 password will always be updated in the device and when set to C(on_create) the
137 password will be updated only if the username is created.
138 type: str
139 default: always
140 choices:
141 - on_create
142 - always
143 group:
144 description:
145 - Configures the group for the username in the device running configuration. The
146 argument accepts a string value defining the group name. This argument does
147 not check if the group has been configured on the device.
148 type: str
149 aliases:
150 - role
151 groups:
152 description:
153 - Configures the groups for the username in the device running configuration.
154 The argument accepts a list of group names. This argument does not check if
155 the group has been configured on the device. It is similar to the aggregate
156 command for usernames, but lets you configure multiple groups for the user(s).
157 type: list
158 elements: str
159 purge:
160 description:
161 - Instructs the module to consider the resource definition absolute. It will remove
162 any previously configured usernames on the device with the exception of the
163 `admin` user and the current defined set of users.
164 type: bool
165 default: false
166 admin:
167 description:
168 - Enters into administration configuration mode for making config changes to the
169 device.
170 - Applicable only when using network_cli transport
171 type: bool
172 default: false
173 state:
174 description:
175 - Configures the state of the username definition as it relates to the device
176 operational configuration. When set to I(present), the username(s) should be
177 configured in the device active configuration and when set to I(absent) the
178 username(s) should not be in the device active configuration
179 type: str
180 default: present
181 choices:
182 - present
183 - absent
184 public_key:
185 description:
186 - Configures the contents of the public keyfile to upload to the IOS-XR node.
187 This enables users to login using the accompanying private key. IOS-XR only
188 accepts base64 decoded files, so this will be decoded and uploaded to the node.
189 Do note that this requires an OpenSSL public key file, PuTTy generated files
190 will not work! Mutually exclusive with public_key_contents. If used with multiple
191 users in aggregates, then the same key file is used for all users.
192 type: str
193 public_key_contents:
194 description:
195 - Configures the contents of the public keyfile to upload to the IOS-XR node.
196 This enables users to login using the accompanying private key. IOS-XR only
197 accepts base64 decoded files, so this will be decoded and uploaded to the node.
198 Do note that this requires an OpenSSL public key file, PuTTy generated files
199 will not work! Mutually exclusive with public_key.If used with multiple users
200 in aggregates, then the same key file is used for all users.
201 type: str
202
203 requirements:
204 - ncclient >= 0.5.3 when using netconf
205 - lxml >= 4.1.1 when using netconf
206 - base64 when using I(public_key_contents) or I(public_key)
207 """
208
209 EXAMPLES = """
210 - name: create a new user
211 cisco.iosxr.iosxr_user:
212 name: ansible
213 configured_password: mypassword
214 state: present
215 - name: create a new user in admin configuration mode
216 cisco.iosxr.iosxr_user:
217 name: ansible
218 configured_password: mypassword
219 admin: true
220 state: present
221 - name: remove all users except admin
222 cisco.iosxr.iosxr_user:
223 purge: true
224 - name: set multiple users to group sys-admin
225 cisco.iosxr.iosxr_user:
226 aggregate:
227 - name: netop
228 - name: netend
229 group: sysadmin
230 state: present
231 - name: set multiple users to multiple groups
232 cisco.iosxr.iosxr_user:
233 aggregate:
234 - name: netop
235 - name: netend
236 groups:
237 - sysadmin
238 - root-system
239 state: present
240 - name: Change Password for User netop
241 cisco.iosxr.iosxr_user:
242 name: netop
243 configured_password: '{{ new_password }}'
244 update_password: always
245 state: present
246 - name: Add private key authentication for user netop
247 cisco.iosxr.iosxr_user:
248 name: netop
249 state: present
250 public_key_contents: "{{ lookup('file', '/home/netop/.ssh/id_rsa.pub' }}"
251 """
252
253 RETURN = """
254 commands:
255 description: The list of configuration mode commands to send to the device
256 returned: always
257 type: list
258 sample:
259 - username ansible secret password group sysadmin
260 - username admin secret admin
261 xml:
262 description: NetConf rpc xml sent to device with transport C(netconf)
263 returned: always (empty list when no xml rpc to send)
264 type: list
265 sample:
266 - '<config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">
267 <aaa xmlns=\"http://cisco.com/ns/yang/Cisco-IOS-XR-aaa-lib-cfg\">
268 <usernames xmlns=\"http://cisco.com/ns/yang/Cisco-IOS-XR-aaa-locald-cfg\">
269 <username xc:operation=\"merge\">
270 <name>test7</name>
271 <usergroup-under-usernames>
272 <usergroup-under-username>
273 <name>sysadmin</name>
274 </usergroup-under-username>
275 </usergroup-under-usernames>
276 <secret>$1$ZsXC$zZ50wqhDC543ZWQkkAHLW0</secret>
277 </username>
278 </usernames>
279 </aaa>
280 </config>'
281 """
282
283 import collections
284
285 from copy import deepcopy
286 from functools import partial
287
288 from ansible.module_utils.basic import AnsibleModule
289 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
290 remove_default_spec,
291 )
292
293 from ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr import (
294 build_xml,
295 copy_file,
296 etree_findall,
297 get_capabilities,
298 get_config,
299 get_connection,
300 is_cliconf,
301 is_netconf,
302 load_config,
303 )
304 from ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.utils.utils import Version
305
306
307 try:
308 from base64 import b64decode
309
310 HAS_B64 = True
311 except ImportError:
312 HAS_B64 = False
313
314
315 class PublicKeyManager(object):
316 def __init__(self, module, result):
317 self._module = module
318 self._result = result
319
320 def convert_key_to_base64(self):
321 """IOS-XR only accepts base64 decoded files, this converts the public key to a temp file."""
322 if self._module.params["aggregate"]:
323 name = "aggregate"
324 else:
325 name = self._module.params["name"]
326
327 if self._module.params["public_key_contents"]:
328 key = self._module.params["public_key_contents"]
329 elif self._module.params["public_key"]:
330 readfile = open(self._module.params["public_key"], "r")
331 key = readfile.read()
332 splitfile = key.split()[1]
333
334 base64key = b64decode(splitfile)
335 base64file = open("/tmp/publickey_%s.b64" % (name), "wb")
336 base64file.write(base64key)
337 base64file.close()
338
339 return "/tmp/publickey_%s.b64" % (name)
340
341 def copy_key_to_node(self, base64keyfile):
342 """Copy key to IOS-XR node. We use SFTP because older IOS-XR versions don't handle SCP very well."""
343
344 if self._module.params["aggregate"]:
345 name = "aggregate"
346 else:
347 name = self._module.params["name"]
348
349 src = base64keyfile
350 dst = "/harddisk:/publickey_%s.b64" % (name)
351
352 copy_file(self._module, src, dst)
353
354 def addremovekey(self, command):
355 """Add or remove key based on command"""
356 admin = self._module.params.get("admin")
357
358 conn = get_connection(self._module)
359 if admin:
360 conn.send_command("admin")
361 out = conn.send_command(command, prompt="yes/no", answer="yes")
362 if admin:
363 conn.send_command("exit")
364
365 return out
366
367 def run(self):
368 if self._module.params["state"] == "present":
369 if not self._module.check_mode:
370 key = self.convert_key_to_base64()
371 self.copy_key_to_node(key)
372
373 if self._module.params["aggregate"]:
374 for user in self._module.params["aggregate"]:
375 cmdtodo = (
376 "crypto key import authentication rsa username %s harddisk:/publickey_aggregate.b64"
377 % (user)
378 )
379 self.addremovekey(cmdtodo)
380 else:
381 cmdtodo = (
382 "crypto key import authentication rsa username %s harddisk:/publickey_%s.b64"
383 % (self._module.params["name"], self._module.params["name"])
384 )
385 self.addremovekey(cmdtodo)
386 elif self._module.params["state"] == "absent":
387 if not self._module.check_mode:
388 if self._module.params["aggregate"]:
389 for user in self._module.params["aggregate"]:
390 cmdtodo = "crypto key zeroize authentication rsa username %s" % (user)
391 self.addremovekey(cmdtodo)
392 else:
393 cmdtodo = "crypto key zeroize authentication rsa username %s" % (
394 self._module.params["name"]
395 )
396 self.addremovekey(cmdtodo)
397 elif self._module.params["purge"] is True:
398 if not self._module.check_mode:
399 cmdtodo = "crypto key zeroize authentication rsa all"
400 self.addremovekey(cmdtodo)
401
402 return self._result
403
404
405 def search_obj_in_list(name, lst):
406 for o in lst:
407 if o["name"] == name:
408 return o
409
410 return None
411
412
413 class ConfigBase(object):
414 def __init__(self, module, result, flag=None):
415 self._module = module
416 self._result = result
417 self._want = list()
418 self._have = list()
419
420 def get_param_value(self, key, item):
421 # if key doesn't exist in the item, get it from module.params
422 if not item.get(key):
423 value = self._module.params[key]
424
425 # if key does exist, do a type check on it to validate it
426 else:
427 value_type = self._module.argument_spec[key].get("type", "str")
428 type_checker = self._module._CHECK_ARGUMENT_TYPES_DISPATCHER[value_type]
429 type_checker(item[key])
430 value = item[key]
431
432 # validate the param value (if validator func exists)
433 validator = globals().get("validate_%s" % key)
434 if all((value, validator)):
435 validator(value, self._module)
436
437 return value
438
439 def map_params_to_obj(self):
440 users = self._module.params["aggregate"]
441
442 aggregate = list()
443 if not users:
444 if not self._module.params["name"] and self._module.params["purge"]:
445 pass
446 elif not self._module.params["name"]:
447 self._module.fail_json(msg="username is required")
448 else:
449 aggregate = [{"name": self._module.params["name"]}]
450 else:
451 for item in users:
452 if not isinstance(item, dict):
453 aggregate.append({"name": item})
454 elif "name" not in item:
455 self._module.fail_json(msg="name is required")
456 else:
457 aggregate.append(item)
458
459 for item in aggregate:
460 get_value = partial(self.get_param_value, item=item)
461 item["configured_password"] = get_value("configured_password")
462 item["group"] = get_value("group")
463 item["groups"] = get_value("groups")
464 item["state"] = get_value("state")
465 self._want.append(item)
466
467
468 class CliConfiguration(ConfigBase):
469 def __init__(self, module, result):
470 super(CliConfiguration, self).__init__(module, result)
471
472 def map_config_to_obj(self):
473 data = get_config(self._module, config_filter="username")
474
475 if "No such configuration item" in data:
476 return
477
478 users = data.strip().rstrip("!").split("!")
479
480 for user in users:
481 user_config = user.strip().splitlines()
482
483 name = user_config[0].strip().split()[1]
484 group = None
485
486 if len(user_config) > 1:
487 group_or_secret = user_config[1].strip().split()
488 if group_or_secret[0] == "group":
489 group = group_or_secret[1]
490
491 obj = {"name": name, "state": "present", "configured_password": None, "group": group}
492 self._have.append(obj)
493
494 def map_obj_to_commands(self):
495 commands = list()
496
497 for w in self._want:
498 name = w["name"]
499 state = w["state"]
500
501 obj_in_have = search_obj_in_list(name, self._have)
502
503 if state == "absent" and obj_in_have:
504 commands.append("no username " + name)
505 elif state == "present" and not obj_in_have:
506 user_cmd = "username " + name
507 commands.append(user_cmd)
508
509 if w["configured_password"]:
510 commands.append(user_cmd + " secret " + w["configured_password"])
511 if w["group"]:
512 commands.append(user_cmd + " group " + w["group"])
513 elif w["groups"]:
514 for group in w["groups"]:
515 commands.append(user_cmd + " group " + group)
516
517 elif state == "present" and obj_in_have:
518 user_cmd = "username " + name
519
520 if self._module.params["update_password"] == "always" and w["configured_password"]:
521 commands.append(user_cmd + " secret " + w["configured_password"])
522 if w["group"] and w["group"] != obj_in_have["group"]:
523 commands.append(user_cmd + " group " + w["group"])
524 elif w["groups"]:
525 for group in w["groups"]:
526 commands.append(user_cmd + " group " + group)
527
528 if self._module.params["purge"]:
529 want_users = [x["name"] for x in self._want]
530 have_users = [x["name"] for x in self._have]
531 for item in set(have_users).difference(set(want_users)):
532 if item != "admin":
533 commands.append("no username %s" % item)
534
535 if "no username admin" in commands:
536 self._module.fail_json(msg="cannot delete the `admin` account")
537
538 self._result["commands"] = []
539 if commands:
540 commit = not self._module.check_mode
541 admin = self._module.params["admin"]
542 diff = load_config(self._module, commands, commit=commit, admin=admin)
543 if diff:
544 self._result["diff"] = dict(prepared=diff)
545
546 self._result["commands"] = commands
547 self._result["changed"] = True
548
549 def run(self):
550 self.map_params_to_obj()
551 self.map_config_to_obj()
552 self.map_obj_to_commands()
553
554 return self._result
555
556
557 class NCConfiguration(ConfigBase):
558 def __init__(self, module, result):
559 super(NCConfiguration, self).__init__(module, result)
560 self._locald_meta = collections.OrderedDict()
561 self._locald_group_meta = collections.OrderedDict()
562
563 def generate_md5_hash(self, arg):
564 """
565 Generate MD5 hash with randomly generated salt size of 3.
566 :param arg:
567 :return passwd:
568 """
569 cmd = "openssl passwd -salt `openssl rand -base64 3` -1 " + arg
570 rc, out, err = self._module.run_command(cmd, use_unsafe_shell=True)
571 if rc != 0:
572 self._module.fail_json(
573 msg="Failed to generate MD5 hash",
574 rc=rc,
575 stdout=out,
576 stderr=err,
577 )
578 return out.strip()
579
580 def map_obj_to_xml_rpc(self, os_version):
581 if os_version and Version(os_version) > Version("7.0"):
582 self._locald_meta.update(
583 [
584 ("aaa_locald", {"xpath": "aaa/usernames", "tag": True, "ns": True}),
585 (
586 "username",
587 {"xpath": "aaa/usernames/username", "tag": True, "attrib": "operation"},
588 ),
589 ("a:name", {"xpath": "aaa/usernames/username/name"}),
590 ("a:ordering_index", {"xpath": "aaa/usernames/username/ordering-index"}),
591 (
592 "secret",
593 {
594 "xpath": "aaa/usernames/username/secret",
595 "tag": True,
596 "operation": "edit",
597 },
598 ),
599 ("a:type", {"xpath": "aaa/usernames/username/secret/type", "value": "type5"}),
600 (
601 "a:configured_password",
602 {"xpath": "aaa/usernames/username/secret/secret5", "operation": "edit"},
603 ),
604 ],
605 )
606 self._locald_group_meta.update(
607 [
608 ("aaa_locald", {"xpath": "aaa/usernames", "tag": True, "ns": True}),
609 (
610 "username",
611 {"xpath": "aaa/usernames/username", "tag": True, "attrib": "operation"},
612 ),
613 ("a:name", {"xpath": "aaa/usernames/username/name"}),
614 ("a:ordering_index", {"xpath": "aaa/usernames/username/ordering-index"}),
615 (
616 "usergroups",
617 {
618 "xpath": "aaa/usernames/username/usergroup-under-usernames",
619 "tag": True,
620 "operation": "edit",
621 },
622 ),
623 (
624 "usergroup",
625 {
626 "xpath": "aaa/usernames/username/usergroup-under-usernames/usergroup-under-username",
627 "tag": True,
628 "operation": "edit",
629 },
630 ),
631 (
632 "a:group",
633 {
634 "xpath": "aaa/usernames/username/usergroup-under-usernames/usergroup-under-username/name",
635 "operation": "edit",
636 },
637 ),
638 ],
639 )
640 else:
641 self._locald_meta.update(
642 [
643 ("aaa_locald", {"xpath": "aaa/usernames", "tag": True, "ns": True}),
644 (
645 "username",
646 {"xpath": "aaa/usernames/username", "tag": True, "attrib": "operation"},
647 ),
648 ("a:name", {"xpath": "aaa/usernames/username/name"}),
649 (
650 "a:configured_password",
651 {"xpath": "aaa/usernames/username/secret", "operation": "edit"},
652 ),
653 ],
654 )
655 self._locald_group_meta.update(
656 [
657 ("aaa_locald", {"xpath": "aaa/usernames", "tag": True, "ns": True}),
658 (
659 "username",
660 {"xpath": "aaa/usernames/username", "tag": True, "attrib": "operation"},
661 ),
662 ("a:name", {"xpath": "aaa/usernames/username/name"}),
663 (
664 "usergroups",
665 {
666 "xpath": "aaa/usernames/username/usergroup-under-usernames",
667 "tag": True,
668 "operation": "edit",
669 },
670 ),
671 (
672 "usergroup",
673 {
674 "xpath": "aaa/usernames/username/usergroup-under-usernames/usergroup-under-username",
675 "tag": True,
676 "operation": "edit",
677 },
678 ),
679 (
680 "a:group",
681 {
682 "xpath": "aaa/usernames/username/usergroup-under-usernames/usergroup-under-username/name",
683 "operation": "edit",
684 },
685 ),
686 ],
687 )
688
689 state = self._module.params["state"]
690 _get_filter = build_xml("aaa", opcode="filter")
691 running = get_config(self._module, source="running", config_filter=_get_filter)
692
693 elements = etree_findall(running, "username")
694 users = list()
695 for element in elements:
696 name_list = etree_findall(element, "name")
697 users.append(name_list[0].text)
698 list_size = len(name_list)
699 if list_size == 1:
700 self._have.append({"name": name_list[0].text, "group": None, "groups": None})
701 elif list_size == 2:
702 self._have.append(
703 {"name": name_list[0].text, "group": name_list[1].text, "groups": None},
704 )
705 elif list_size > 2:
706 name_iter = iter(name_list)
707 next(name_iter)
708 tmp_list = list()
709 for name in name_iter:
710 tmp_list.append(name.text)
711
712 self._have.append({"name": name_list[0].text, "group": None, "groups": tmp_list})
713 if os_version and Version(os_version) > Version("7.0"):
714 ordering_index = etree_findall(element, "ordering-index")
715 if len(self._have) > 0:
716 self._have[-1].update(ordering_index=ordering_index[0].text)
717
718 locald_params = list()
719 locald_group_params = list()
720 opcode = None
721 ordering_index_list = [
722 int(user.get("ordering_index")) for user in self._have if user.get("ordering_index")
723 ]
724
725 if state == "absent":
726 opcode = "delete"
727 for want_item in self._want:
728 if want_item["name"] in users:
729 obj_in_have = search_obj_in_list(want_item["name"], self._have)
730 if os_version and Version(os_version) > Version("7.0"):
731 want_item["ordering_index"] = obj_in_have["ordering_index"]
732 want_item["configured_password"] = None
733 locald_params.append(want_item)
734 elif state == "present":
735 opcode = "merge"
736 for want_item in self._want:
737 obj_in_have = search_obj_in_list(want_item["name"], self._have)
738 if want_item["name"] not in users:
739 if os_version and Version(os_version) > Version("7.0"):
740 want_item["configured_password"] = self.generate_md5_hash(
741 want_item["configured_password"],
742 )
743 new_ordering_index = ordering_index_list[-1] + 1
744 want_item["ordering_index"] = str(new_ordering_index)
745 ordering_index_list.append(new_ordering_index)
746 want_item["type"] = "type5"
747 want_item["configured_password"] = self.generate_md5_hash(
748 want_item["configured_password"],
749 )
750 locald_params.append(want_item)
751 if want_item["group"] is not None:
752 locald_group_params.append(want_item)
753 if want_item["groups"] is not None:
754 for group in want_item["groups"]:
755 want_item["group"] = group
756 locald_group_params.append(want_item.copy())
757 else:
758 if os_version and Version(os_version) > Version("7.0"):
759 if obj_in_have:
760 # Add iosxr 7.0 > specific parameters
761 want_item["type"] = "type5"
762 want_item["ordering_index"] = obj_in_have["ordering_index"]
763 if (
764 self._module.params["update_password"] == "always"
765 and want_item["configured_password"] is not None
766 ):
767 want_item["configured_password"] = self.generate_md5_hash(
768 want_item["configured_password"],
769 )
770 locald_params.append(want_item)
771 else:
772 want_item["configured_password"] = None
773
774 if (
775 want_item["group"] is not None
776 and want_item["group"] != obj_in_have["group"]
777 ):
778 locald_group_params.append(want_item)
779 elif want_item["groups"] is not None:
780 for group in want_item["groups"]:
781 want_item["group"] = group
782 locald_group_params.append(want_item.copy())
783
784 purge_params = list()
785 if self._module.params["purge"]:
786 want_users = [x["name"] for x in self._want]
787 have_users = [x["name"] for x in self._have]
788 for item in set(have_users).difference(set(want_users)):
789 if item != "admin":
790 purge_params.append({"name": item})
791
792 self._result["xml"] = []
793 _edit_filter_list = list()
794 if opcode is not None:
795 if locald_params:
796 _edit_filter_list.append(
797 build_xml("aaa", xmap=self._locald_meta, params=locald_params, opcode=opcode),
798 )
799
800 if locald_group_params:
801 _edit_filter_list.append(
802 build_xml(
803 "aaa",
804 xmap=self._locald_group_meta,
805 params=locald_group_params,
806 opcode=opcode,
807 ),
808 )
809
810 if purge_params:
811 _edit_filter_list.append(
812 build_xml("aaa", xmap=self._locald_meta, params=purge_params, opcode="delete"),
813 )
814 diff = None
815 if _edit_filter_list:
816 commit = not self._module.check_mode
817 diff = load_config(
818 self._module,
819 _edit_filter_list,
820 commit=commit,
821 running=running,
822 nc_get_filter=_get_filter,
823 )
824
825 if diff:
826 if self._module._diff:
827 self._result["diff"] = dict(prepared=diff)
828
829 self._result["xml"] = _edit_filter_list
830 self._result["changed"] = True
831
832 def run(self):
833 os_version = get_capabilities(self._module).get("device_info").get("network_os_version")
834 self.map_params_to_obj()
835 self.map_obj_to_xml_rpc(os_version)
836
837 return self._result
838
839
840 def main():
841 """main entry point for module execution"""
842 element_spec = dict(
843 name=dict(type="str"),
844 configured_password=dict(type="str", no_log=True),
845 update_password=dict(type="str", default="always", choices=["on_create", "always"]),
846 admin=dict(type="bool", default=False),
847 public_key=dict(type="str"),
848 public_key_contents=dict(type="str"),
849 group=dict(type="str", aliases=["role"]),
850 groups=dict(type="list", elements="str"),
851 state=dict(type="str", default="present", choices=["present", "absent"]),
852 )
853 aggregate_spec = deepcopy(element_spec)
854 aggregate_spec["name"] = dict(required=True)
855
856 # remove default in aggregate spec, to handle common arguments
857 remove_default_spec(aggregate_spec)
858
859 mutually_exclusive = [
860 ("name", "aggregate"),
861 ("public_key", "public_key_contents"),
862 ("group", "groups"),
863 ]
864
865 argument_spec = dict(
866 aggregate=dict(
867 type="list",
868 elements="dict",
869 options=aggregate_spec,
870 aliases=["users", "collection"],
871 ),
872 purge=dict(type="bool", default=False),
873 )
874
875 argument_spec.update(element_spec)
876
877 module = AnsibleModule(
878 argument_spec=argument_spec,
879 mutually_exclusive=mutually_exclusive,
880 supports_check_mode=True,
881 )
882
883 if module.params["public_key_contents"] or module.params["public_key"]:
884 if not HAS_B64:
885 module.fail_json(
886 msg="library base64 is required but does not appear to be "
887 "installed. It can be installed using `pip install base64`",
888 )
889
890 result = {"changed": False, "warnings": []}
891
892 config_object = None
893 if is_cliconf(module):
894 # Commenting the below cliconf deprecation support call for Ansible 2.9 as it'll be continued to be supported
895 config_object = CliConfiguration(module, result)
896 elif is_netconf(module):
897 config_object = NCConfiguration(module, result)
898
899 if config_object:
900 result = config_object.run()
901
902 if module.params["public_key_contents"] or module.params["public_key"]:
903 pubkey_object = PublicKeyManager(module, result)
904 result = pubkey_object.run()
905
906 module.exit_json(**result)
907
908
909 if __name__ == "__main__":
910 main()