Merge branch 'nigelm_freebsd' of git://github.com/nigelm/ansible into merge-service

Make things more reusable, correct some errors along the SSH key path

Conflicts:
	library/user
reviewable/pr18780/r1
Michael DeHaan 12 years ago
commit 61a4674413

764
user

@ -103,9 +103,10 @@ options:
description: description:
- When used with I(state=absent), behavior is as with - When used with I(state=absent), behavior is as with
I(userdel --remove). I(userdel --remove).
ssh_key: generate_ssh_key:
required: false required: false
choices: [ generate ] default: "no"
choices: [ yes, no ]
version_added: "0.9" version_added: "0.9"
description: description:
- Whether to generate a SSH key for the user in question. - Whether to generate a SSH key for the user in question.
@ -155,111 +156,169 @@ examples:
import os import os
import pwd import pwd
import grp import grp
import syslog
import platform
try: try:
import spwd import spwd
HAVE_SPWD=True HAVE_SPWD=True
except: except:
HAVE_SPWD=False HAVE_SPWD=False
SHADOWFILE = '/etc/shadow'
if os.path.exists('/etc/master.passwd'): class User(object):
SHADOWFILE = '/etc/master.passwd' # FreeBSD passwd """
# Note: while the above has the correct location for where This is a generic User manipulation class that is subclassed
# encrypted passwords are stored on FreeBSD, the code below doesn't based on platform.
# invoke adduser in lieu of useradd, nor pw in lieu of usermod.
# That is, this won't work on FreeBSD. A subclass may wish to override the following action methods:-
- create_user()
def user_del(module, user, **kwargs): - remove_user()
cmd = [module.get_bin_path('userdel', True)] - modify_user()
for key in kwargs: - ssh_key_gen()
if key == 'force' and module.boolean(kwargs[key]): - ssh_key_fingerprint()
- user_exists()
All subclasses MUST define platform and distribution (which may be None).
"""
platform = 'Generic'
distribution = None
SHADOWFILE = '/etc/shadow'
def __new__(cls, *args, **kwargs):
return load_platform_subclass(User, args, kwargs)
def __init__(self, module):
self.module = module
self.state = module.params['state']
self.name = module.params['name']
self.uid = module.params['uid']
self.group = module.params['group']
self.groups = module.params['groups']
self.comment = module.params['comment']
self.home = module.params['home']
self.shell = module.params['shell']
self.password = module.params['password']
self.force = module.boolean(module.params['force'])
self.remove = module.boolean(module.params['remove'])
self.createhome = module.boolean(module.params['createhome'])
self.system = module.boolean(module.params['system'])
self.append = module.boolean(module.params['append'])
self.sshkeygen = module.boolean(module.params['generate_ssh_key'])
self.ssh_bits = module.params['ssh_key_bits']
self.ssh_type = module.params['ssh_key_type']
self.ssh_comment = module.params['ssh_key_comment']
self.ssh_passphrase = module.params['ssh_key_passphrase']
if module.params['ssh_key_file'] is not None:
self.ssh_file = module.params['ssh_key_file']
else:
self.ssh_file = os.path.join('.ssh', 'id_%s' % self.ssh_type)
# select whether we dump additional debug info through syslog
self.syslogging = False
def execute_command(self,cmd):
if self.syslogging:
syslog.openlog('ansible-%s' % os.path.basename(__file__))
syslog.syslog(syslog.LOG_NOTICE, 'Command %s' % '|'.join(cmd))
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
rc = p.returncode
return (rc, out, err)
def remove_user_userdel(self):
cmd = [self.module.get_bin_path('userdel', True)]
if self.force:
cmd.append('-f') cmd.append('-f')
elif key == 'remove' and module.boolean(kwargs[key]): elif self.remove:
cmd.append('-r') cmd.append('-r')
cmd.append(user) cmd.append(self.name)
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate() return self.execute_command(cmd)
rc = p.returncode
return (rc, out, err) def create_user_useradd(self, command_name='useradd'):
cmd = [self.module.get_bin_path(command_name, True)]
def user_add(module, user, **kwargs):
cmd = [module.get_bin_path('useradd', True)] if self.uid is not None:
for key in kwargs:
if key == 'uid' and kwargs[key] is not None:
cmd.append('-u') cmd.append('-u')
cmd.append(kwargs[key]) cmd.append(self.uid)
elif key == 'group' and kwargs[key] is not None:
if not group_exists(kwargs[key]): if self.group is not None:
module.fail_json(msg="Group %s does not exist" % (kwargs[key])) if not user.group_exists(self.group):
self.module.fail_json(msg="Group %s does not exist" % self.group)
cmd.append('-g') cmd.append('-g')
cmd.append(kwargs[key]) cmd.append(self.group)
elif key == 'groups' and kwargs[key] is not None:
for g in kwargs[key].split(','): if self.groups is not None:
if not group_exists(g): for g in self.groups.split(','):
module.fail_json(msg="Group %s does not exist" % (g)) if not self.group_exists(g):
self.module.fail_json(msg="Group %s does not exist" % (g))
cmd.append('-G') cmd.append('-G')
cmd.append(kwargs[key]) cmd.append(self.groups)
elif key == 'comment' and kwargs[key] is not None:
if self.comment is not None:
cmd.append('-c') cmd.append('-c')
cmd.append(kwargs[key]) cmd.append(self.comment)
elif key == 'home' and kwargs[key] is not None:
if self.home is not None:
cmd.append('-d') cmd.append('-d')
cmd.append(kwargs[key]) cmd.append(self.home)
elif key == 'shell' and kwargs[key] is not None:
if self.shell is not None:
cmd.append('-s') cmd.append('-s')
cmd.append(kwargs[key]) cmd.append(self.shell)
elif key == 'password' and kwargs[key] is not None:
if self.password is not None:
cmd.append('-p') cmd.append('-p')
cmd.append(kwargs[key]) cmd.append(self.password)
elif key == 'createhome':
if kwargs[key] is not None: if self.createhome:
value = module.boolean(kwargs[key]) cmd.append('-m')
if value: else:
cmd.append('-m') cmd.append('-M')
else:
cmd.append('-M') if self.system:
elif key == 'system' and module.boolean(kwargs[key]):
cmd.append('-r') cmd.append('-r')
cmd.append(user)
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cmd.append(self.name)
(out, err) = p.communicate() return self.execute_command(cmd)
rc = p.returncode
return (rc, out, err)
def modify_user_usermod(self):
""" cmd = [self.module.get_bin_path('usermod', True)]
Without spwd, we would have to resort to reading /etc/shadow info = self.user_info()
to get the encrypted string. For now, punt on idempotent password changes.
""" if self.uid is not None and info[2] != int(self.uid):
def user_mod(module, user, **kwargs): cmd.append('-u')
cmd = [module.get_bin_path('usermod', True)] cmd.append(self.uid)
info = user_info(user)
for key in kwargs: if self.group is not None:
if key == 'uid': if not self.group_exists(self.group):
if kwargs[key] is not None and info[2] != int(kwargs[key]): module.fail_json(msg="Group %s does not exist" % self.group)
cmd.append('-u') ginfo = self.group_info(self.group)
cmd.append(kwargs[key])
elif key == 'group' and kwargs[key] is not None:
if not group_exists(kwargs[key]):
module.fail_json(msg="Group %s does not exist" % (kwargs[key]))
ginfo = group_info(kwargs[key])
if info[3] != ginfo[2]: if info[3] != ginfo[2]:
cmd.append('-g') cmd.append('-g')
cmd.append(kwargs[key]) cmd.append(self.group)
elif key == 'groups' and kwargs[key] is not None:
current_groups = user_group_membership(user) if self.groups is not None:
groups = kwargs[key].split(',') current_groups = self.user_group_membership()
groups = self.groups.split(',')
for g in groups: for g in groups:
if not group_exists(g): if not self.group_exists(g):
module.fail_json(msg="Group %s does not exist" % (g)) module.fail_json(msg="Group %s does not exist" % (g))
group_diff = set(sorted(current_groups)).symmetric_difference(set(sorted(groups))) group_diff = set(sorted(current_groups)).symmetric_difference(set(sorted(groups)))
groups_need_mod = False groups_need_mod = False
if group_diff: if group_diff:
if kwargs['append'] is not None and module.boolean(kwargs['append']): if self.append:
for g in groups: for g in groups:
if g in group_diff: if g in group_diff:
cmd.append('-a') cmd.append('-a')
groups_need_mod = True groups_need_mod = True
break
else: else:
groups_need_mod = True groups_need_mod = True
@ -267,161 +326,314 @@ def user_mod(module, user, **kwargs):
cmd.append('-G') cmd.append('-G')
cmd.append(','.join(groups)) cmd.append(','.join(groups))
elif key == 'comment': if self.comment is not None and info[4] != self.comment:
if kwargs[key] is not None and info[4] != kwargs[key]:
cmd.append('-c') cmd.append('-c')
cmd.append(kwargs[key]) cmd.append(self.comment)
elif key == 'home':
if kwargs[key] is not None and info[5] != kwargs[key]: if self.home is not None and info[5] != self.home:
cmd.append('-d') cmd.append('-d')
cmd.append(kwargs[key]) cmd.append(self.home)
elif key == 'shell':
if kwargs[key] is not None and info[6] != kwargs[key]: if self.shell is not None and info[6] != self.shell:
cmd.append('-s') cmd.append('-s')
cmd.append(kwargs[key]) cmd.append(self.shell)
elif key == 'password':
if kwargs[key] is not None and info[1] != kwargs[key]: if self.password is not None and info[1] != self.password:
cmd.append('-p') cmd.append('-p')
cmd.append(kwargs[key]) cmd.append(self.password)
# skip if no changes to be made
if len(cmd) == 1: # skip if no changes to be made
return (None, '', '') if len(cmd) == 1:
cmd.append(user) return (None, '', '')
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate() cmd.append(self.name)
rc = p.returncode return self.execute_command(cmd)
return (rc, out, err)
def group_exists(self,group):
def group_exists(group): try:
try: if group.isdigit():
if grp.getgrgid(group):
return True
else:
if grp.getgrnam(group):
return True
except KeyError:
return False
def group_info(self,group):
if not self.group_exists(group):
return False
if group.isdigit(): if group.isdigit():
if grp.getgrgid(group): return list(grp.getgrgid(group))
return True
else: else:
if grp.getgrnam(group): return list(grp.getgrnam(group))
return True
except KeyError: def user_group_membership(self):
return False groups = []
info = self.get_pwd_info()
def group_info(group): for group in grp.getgrall():
if not group_exists(group): if self.name in group[3] and info[3] != group[2]:
return False groups.append(group[0])
if group.isdigit(): return groups
return list(grp.getgrgid(group))
else: def user_exists(self):
return list(grp.getgrnam(group))
def user_group_membership(user):
groups = []
info = get_pwd_info(user)
for group in grp.getgrall():
if user in group[3]:
groups.append(group[0])
return groups
def user_exists(user):
try:
if pwd.getpwnam(user):
return True
except KeyError:
return False
def get_pwd_info(user):
if not user_exists(user):
return False
return list(pwd.getpwnam(user))
def user_info(user):
if not user_exists(user):
return False
info = get_pwd_info(user)
if len(info[1]) == 1 or len(info[1]) == 0:
info[1] = user_password(user)
return info
def user_password(user):
passwd = ''
if not user_exists(user):
return passwd
if HAVE_SPWD:
try: try:
passwd = spwd.getspnam(user)[1] if pwd.getpwnam(self.name):
return True
except KeyError: except KeyError:
return False
def get_pwd_info(self):
if not self.user_exists():
return False
return list(pwd.getpwnam(self.name))
def user_info(self):
if not self.user_exists():
return False
info = self.get_pwd_info()
if len(info[1]) == 1 or len(info[1]) == 0:
info[1] = self.user_password()
return info
def user_password(self):
passwd = ''
if HAVE_SPWD:
try:
passwd = spwd.getspnam(self.name)[1]
except KeyError:
return passwd
if not self.user_exists():
return passwd return passwd
else: else:
# Read shadow file for user's encrypted password string # Read shadow file for user's encrypted password string
if os.path.exists(SHADOWFILE) and os.access(SHADOWFILE, os.R_OK): if os.path.exists(User.SHADOWFILE) and os.access(User.SHADOWFILE, os.R_OK):
for line in open(SHADOWFILE).readlines(): for line in open(User.SHADOWFILE).readlines():
if line.startswith('%s:' % user): if line.startswith('%s:' % self.name):
passwd = line.split(':')[1] passwd = line.split(':')[1]
return passwd return passwd
def get_ssh_key_path(user, ssh_file): def get_ssh_key_path(self):
info = user_info(user) info = self.user_info()
if os.path.isabs(ssh_file): if os.path.isabs(self.ssh_file):
ssh_key_file = ssh_file ssh_key_file = self.ssh_file
else: else:
ssh_key_file = os.path.join(info[5], ssh_file) ssh_key_file = os.path.join(info[5], self.ssh_file)
return ssh_key_file return ssh_key_file
def ssh_key_gen(module, user, ssh): def ssh_key_gen(self):
info = user_info(user) info = self.user_info()
if not os.path.exists(info[5]): if not os.path.exists(info[5]):
return (1, '', 'User %s home directory does not exist' % user) return (1, '', 'User %s home directory does not exist' % self.name)
ssh_key_file = get_ssh_key_path(user, ssh['file']) ssh_key_file = self.get_ssh_key_path()
ssh_dir = os.path.dirname(ssh_key_file) ssh_dir = os.path.dirname(ssh_key_file)
if not os.path.exists(ssh_dir): if not os.path.exists(ssh_dir):
try: try:
os.mkdir(ssh_dir, 0700) os.mkdir(ssh_dir, 0700)
os.chown(ssh_dir, info[2], info[3]) except OSError, e:
except OSError, e: return (1, '', 'Failed to create %s: %s' % (ssh_dir, str(e)))
return (1, '', 'Failed to create %s: %s' % (ssh_dir, str(e))) if os.path.exists(ssh_key_file):
if os.path.exists(ssh_key_file): return (None, 'Key already exists', '')
return (None, 'Key already exists', '') cmd = [self.module.get_bin_path('ssh-keygen', True)]
cmd = [module.get_bin_path('ssh-keygen', True)] cmd.append('-t')
for key in ssh: cmd.append(self.ssh_type)
if key == 'type' and ssh[key] is not None: cmd.append('-b')
cmd.append('-t') cmd.append(self.ssh_bits)
cmd.append(ssh[key]) cmd.append('-C')
elif key == 'bits' and ssh[key] is not None: cmd.append(self.ssh_comment)
cmd.append('-b') cmd.append('-f')
cmd.append(ssh[key]) cmd.append(ssh_key_file)
elif key == 'comment' and ssh[key] is not None: cmd.append('-N')
cmd.append('-C') if self.ssh_passphrase is not None:
cmd.append(ssh[key]) cmd.append(self.ssh_passphrase)
elif key == 'file' and ssh[key] is not None: else:
cmd.append('-f') cmd.append('')
cmd.append(ssh_key_file)
elif key == 'passphrase': p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
cmd.append('-N') (out, err) = p.communicate()
if ssh[key] is not None: rc = p.returncode
cmd.append(ssh['passphrase']) if rc == 0:
else: # If the keys were successfully created, we should be able
cmd.append('') # to tweak ownership.
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) os.chown(ssh_key_file, info[2], info[3])
(out, err) = p.communicate() os.chown('%s.pub' % ssh_key_file, info[2], info[3])
rc = p.returncode return (rc, out, err)
if rc == 0:
# If the keys were successfully created, we should be able def ssh_key_fingerprint(self):
# to tweak ownership. ssh_key_file = self.get_ssh_key_path()
os.chown(ssh_key_file, info[2], info[3]) if not os.path.exists(ssh_key_file):
os.chown('%s.pub' % ssh_key_file, info[2], info[3]) return (1, 'SSH Key file %s does not exist' % ssh_key_file, '')
return (rc, out, err) cmd = [ self.module.get_bin_path('ssh-keygen', True) ]
cmd.append('-l')
def ssh_key_fingerprint(module, user, ssh): cmd.append('-f')
ssh_key_file = get_ssh_key_path(user, ssh['file']) cmd.append(ssh_key_file)
if not os.path.exists(ssh_key_file):
return (1, 'SSH Key file %s does not exist' % ssh_key_file, '') return self.execute_command(cmd)
cmd = [module.get_bin_path('ssh-keygen', True)]
cmd.append('-l') def create_user(self):
cmd.append('-f') # by default we use the create_user_useradd method
cmd.append(ssh_key_file) return self.create_user_useradd()
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate() def remove_user(self):
rc = p.returncode # by default we use the remove_user_userdel method
return (rc, out, err) return self.remove_user_userdel()
def modify_user(self):
# by default we use the modify_user_usermod method
return self.modify_user_usermod()
# ===========================================
class FreeBsdUser(User):
"""
This is a FreeBSD User manipulation class - it uses the pw command
to manipulate the user database, followed by the chpass command
to change the password.
This overrides the following methods from the generic class:-
- create_user()
- remove_user()
- modify_user()
"""
platform = 'FreeBSD'
distribution = None
SHADOWFILE = '/etc/master.passwd'
def remove_user(self):
cmd = [self.module.get_bin_path('pw', True),
'userdel',
'-n',
self.name ]
if self.remove:
cmd.append('-r')
return self.execute_command(cmd)
def create_user(self):
cmd = [self.module.get_bin_path('pw', True),
'useradd',
'-n',
self.name ]
if self.uid is not None:
cmd.append('-u')
cmd.append(self.uid)
if self.comment is not None:
cmd.append('-c')
cmd.append(self.comment)
if self.home is not None:
cmd.append('-d')
cmd.append(self.home)
if self.group is not None:
if not user.group_exists(self.group):
self.module.fail_json(msg="Group %s does not exist" % self.group)
cmd.append('-g')
cmd.append(self.group)
if self.groups is not None:
for g in self.groups.split(','):
if not self.group_exists(g):
self.module.fail_json(msg="Group %s does not exist" % (g))
cmd.append('-G')
cmd.append(self.groups)
if self.createhome:
cmd.append('-m')
if self.shell is not None:
cmd.append('-s')
cmd.append(self.shell)
# system cannot be handled currently - should we error if its requested?
# create the user
(rc, out, err) = self.execute_command(cmd)
if rc is not None and rc != 0:
module.fail_json(name=self.name, msg=err, rc=rc)
# we have to set the password in a second command
if self.password is not None:
cmd = [self.module.get_bin_path('chpass', True),
'-p',
self.password,
self.name ]
return self.execute_command(cmd)
return (rc, out, err)
def modify_user(self):
cmd = [self.module.get_bin_path('pw', True),
'usermod',
'-n',
self.name ]
info = self.user_info()
if self.uid is not None and info[2] != int(self.uid):
cmd.append('-u')
cmd.append(self.uid)
if self.comment is not None and info[4] != self.comment:
cmd.append('-c')
cmd.append(self.comment)
if self.home is not None and info[5] != self.home:
cmd.append('-d')
cmd.append(self.home)
if self.group is not None:
if not user.group_exists(self.group):
self.module.fail_json(msg="Group %s does not exist" % self.group)
ginfo = self.group_info(self.group)
if info[3] != ginfo[2]:
cmd.append('-g')
cmd.append(self.group)
if self.shell is not None and info[6] != self.shell:
cmd.append('-s')
cmd.append(self.shell)
if self.groups is not None:
current_groups = self.user_group_membership()
groups = self.groups.split(',')
for g in groups:
if not self.group_exists(g):
module.fail_json(msg="Group %s does not exist" % (g))
group_diff = set(sorted(current_groups)).symmetric_difference(set(sorted(groups)))
groups_need_mod = False
if group_diff:
if self.append:
for g in groups:
if g in group_diff:
groups_need_mod = True
break
else:
groups_need_mod = True
if groups_need_mod:
new_groups = groups
if self.append:
new_groups.append(current_groups)
cmd.append(','.join(new_groups))
# modify the user
(rc, out, err) = self.execute_command(cmd)
if rc is not None and rc != 0:
module.fail_json(name=self.name, msg=err, rc=rc)
# we have to set the password in a second command
if self.password is not None and info[1] != self.password:
cmd = [self.module.get_bin_path('chpass', True),
'-p',
self.password,
self.name ]
return self.execute_command(cmd)
return (rc, out, err)
# =========================================== # ===========================================
@ -432,8 +644,6 @@ def main():
'passphrase': None, 'passphrase': None,
'comment': 'ansible-generated' 'comment': 'ansible-generated'
} }
ssh_defaults['file'] = os.path.join('.ssh', 'id_%s' % ssh_defaults['type'])
ssh = dict(ssh_defaults)
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec = dict(
state=dict(default='present', choices=['present', 'absent']), state=dict(default='present', choices=['present', 'absent']),
@ -454,72 +664,47 @@ def main():
# following options are specific to usermod # following options are specific to usermod
append=dict(default='no', choices=BOOLEANS), append=dict(default='no', choices=BOOLEANS),
# following are specific to ssh key generation # following are specific to ssh key generation
ssh_key=dict(choices=['generate']), generate_ssh_key=dict(choices=BOOLEANS),
ssh_key_bits=dict(default=ssh_defaults['bits']), ssh_key_bits=dict(default=ssh_defaults['bits']),
ssh_key_type=dict(default=ssh_defaults['type']), ssh_key_type=dict(default=ssh_defaults['type']),
ssh_key_file=dict(default=ssh_defaults['file']), ssh_key_file=dict(default=None),
ssh_key_comment=dict(default=ssh_defaults['comment']), ssh_key_comment=dict(default=ssh_defaults['comment']),
ssh_key_passphrase=dict(default=None) ssh_key_passphrase=dict(default=None)
) )
) )
state = module.params['state'] user = User(module)
name = module.params['name']
uid = module.params['uid']
group = module.params['group']
groups = module.params['groups']
comment = module.params['comment']
home = module.params['home']
shell = module.params['shell']
password = module.params['password']
force = module.params['force']
remove = module.params['remove']
createhome = module.params['createhome']
system = module.params['system']
append = module.params['append']
sshkeygen = module.params['ssh_key']
ssh['bits'] = module.params['ssh_key_bits']
ssh['type'] = module.params['ssh_key_type']
ssh['file'] = module.params['ssh_key_file']
ssh['comment'] = module.params['ssh_key_comment']
ssh['passphrase'] = module.params['ssh_key_passphrase']
# If using default filename, make sure it is named appropriately
if ssh['file'] == ssh_defaults['file']:
ssh['file'] = os.path.join('.ssh', 'id_%s' % ssh_defaults['type'])
if user.syslogging:
syslog.openlog('ansible-%s' % os.path.basename(__file__))
syslog.syslog(syslog.LOG_NOTICE, 'User instantiated - platform %s' % user.platform)
if user.distribution:
syslog.syslog(syslog.LOG_NOTICE, 'User instantiated - distribution %s' % user.distribution)
rc = None rc = None
out = '' out = ''
err = '' err = ''
result = {} result = {}
result['name'] = name result['name'] = user.name
result['state'] = state result['state'] = user.state
if state == 'absent': if user.state == 'absent':
if user_exists(name): if user.user_exists():
(rc, out, err) = user_del(module, name, force=force, remove=remove) (rc, out, err) = user.remove_user()
if rc != 0: if rc != 0:
module.fail_json(name=name, msg=err, rc=rc) module.fail_json(name=name, msg=err, rc=rc)
result['force'] = force result['force'] = user.force
result['remove'] = remove result['remove'] = user.remove
elif state == 'present': elif user.state == 'present':
if not user_exists(name): if not user.user_exists():
(rc, out, err) = user_add(module, (rc, out, err) = user.create_user()
name, uid=uid, group=group, groups=groups, result['system'] = user.system
comment=comment, home=home, shell=shell, result['createhome'] = user.createhome
password=password, createhome=createhome,
system=system)
result['system'] = system
result['createhome'] = createhome
else: else:
(rc, out, err) = user_mod(module, (rc, out, err) = user.modify_user()
name, uid=uid, group=group, groups=groups, result['append'] = user.append
comment=comment, home=home, shell=shell,
password=password, append=append)
result['append'] = append
if rc is not None and rc != 0: if rc is not None and rc != 0:
module.fail_json(name=name, msg=err, rc=rc) module.fail_json(name=user.name, msg=err, rc=rc)
if password is not None: if user.password is not None:
result['password'] = 'NOT_LOGGING_PASSWORD' result['password'] = 'NOT_LOGGING_PASSWORD'
if rc is None: if rc is None:
@ -530,32 +715,35 @@ def main():
result['stdout'] = out result['stdout'] = out
if err: if err:
result['stderr'] = err result['stderr'] = err
if user_exists(name):
info = user_info(name) if user.user_exists():
info = user.user_info()
if info == False: if info == False:
result['msg'] = "failed to look up user name: %s" % name result['msg'] = "failed to look up user name: %s" % user.name
result['failed'] = True result['failed'] = True
result['uid'] = info[2] result['uid'] = info[2]
result['group'] = info[3] result['group'] = info[3]
result['comment'] = info[4] result['comment'] = info[4]
result['home'] = info[5] result['home'] = info[5]
result['shell'] = info[6] result['shell'] = info[6]
groups = user_group_membership(name) groups = user.user_group_membership()
result['uid'] = info[2] result['uid'] = info[2]
if len(groups) > 0: if user.groups is not None:
result['groups'] = groups result['groups'] = user.groups
if sshkeygen:
(rc, out, err) = ssh_key_gen(module, name, ssh) # deal with ssh key
if user.sshkeygen:
(rc, out, err) = user.ssh_key_gen()
if rc is not None and rc != 0: if rc is not None and rc != 0:
module.fail_json(name=name, msg=err, rc=rc) module.fail_json(name=user.name, msg=err, rc=rc)
if rc == 0: if rc == 0:
result['changed'] = True result['changed'] = True
(rc, out, err) = ssh_key_fingerprint(module, name, ssh) (rc, out, err) = user.ssh_key_fingerprint()
if rc == 0: if rc == 0:
result['ssh_fingerprint'] = out.strip() result['ssh_fingerprint'] = out.strip()
else: else:
result['ssh_fingerprint'] = err.strip() result['ssh_fingerprint'] = err.strip()
result['ssh_key_file'] = get_ssh_key_path(name, ssh['file']) result['ssh_key_file'] = user.get_ssh_key_path()
module.exit_json(**result) module.exit_json(**result)

Loading…
Cancel
Save