Skip to content

Instantly share code, notes, and snippets.

@mgedmin
Created July 4, 2024 10:17
Show Gist options
  • Save mgedmin/ee6047e9df97d5953c217ba897759d35 to your computer and use it in GitHub Desktop.
Save mgedmin/ee6047e9df97d5953c217ba897759d35 to your computer and use it in GitHub Desktop.
Ansible module to lock a user account
#!/usr/bin/python
import spwd
import subprocess
DOCUMENTATION = '''
---
module: lock_user
short_description: locks user accounts
description:
- The M(lock_user) module invokes C(passwd -l) to lock user accounts.
options:
user:
description:
- the name of the user account to lock
required: true
default: null
must_exist:
description:
- if true, and if the named user account doesn't exist, fails
required: false
choices: [ true, false ]
default: false
author:
- Marius Gedminas <marius@pov.lt>
'''
RETURN = '''
user_exists:
description: User account exists
returned: success
type: bool
'''
EXAMPLES = '''
- lock_user: user=bob must_exist=true
- lock_user: user={{ item }}
with_items:
- fred
- barney
'''
def run(args, module):
try:
cmd = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
rc = cmd.returncode
except (OSError, IOError) as e:
module.fail_json(rc=e.errno, msg=str(e), cmd=args)
if rc != 0 or err:
module.fail_json(rc=rc, msg=err, cmd=args)
return out
def main():
module = AnsibleModule(
argument_spec=dict(
user=dict(type='str', required=True),
must_exist=dict(type='bool', default=False),
),
supports_check_mode=True,
)
user = module.params['user']
must_exist = module.params['must_exist']
try:
pwhash = spwd.getspnam(user).sp_pwd
is_locked = pwhash.startswith('!') or pwhash == '*'
except PermissionError:
module.fail_json(msg="cannot read /etc/shadow")
except KeyError:
if must_exist:
module.fail_json(msg="user %s doest not exist" % user)
else:
module.exit_json(
user_exists=False,
changed=False,
)
if is_locked:
module.exit_json(
user_exists=True,
changed=False,
)
if not module.check_mode:
run(['passwd', '-l', user], module)
module.exit_json(
user_exists=True,
changed=True,
)
from ansible.module_utils.basic import * # noqa
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment