使用Ansible锁定用户的方法

38次阅读
没有评论

问题描述

在使用Ansible时,有一个需求是通过给定用户名来锁定用户。如果该用户存在,则将其锁定;否则保持缺失状态。最可能的模块是ansible.builtin.user。通常,通过在ansible.builtin.user模块中传递password: "*"shell: "/usr/sbin/nologin"可以实现锁定行为,但这也会创建用户。state属性只有presentabsent两个可能的值,都无法描述所需的行为。可以通过使用ansible.builtin.getent获取有关用户存在的事实,然后有条件地使用ansible.builtin.user。是否有更好的方法?

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1 – 使用ansible.builtin.user模块和条件语句

目前,尽管可能需要使用多个任务,但使用ansible.builtin.user模块和条件语句是实现锁定用户的推荐方法。在这个方案中,我们首先使用ansible.builtin.getent模块来检查用户是否存在,然后根据检查结果执行相应的操作。

以下是一个示例的Ansible Playbook,演示如何通过用户名锁定用户:

---
- name: Lock User
  hosts: your_target_host
  tasks:
    - name: Check if user exists
      ansible.builtin.getent:
        database: passwd
        key: "{{ user_name }}"
      register: user_check

    - name: Lock user if exists
      ansible.builtin.user:
        name: "{{ user_name }}"
        password: "*"
        shell: "/usr/sbin/nologin"
        state: present
      when: user_check.key is defined

    - name: Report user locked
      debug:
        msg: "User {{ user_name }} locked."
      when: user_check.key is defined

在上面的示例中,我们首先使用ansible.builtin.getent模块来检查用户是否存在。然后,在ansible.builtin.user模块中使用条件语句,仅当用户存在时才锁定用户。最后,使用ansible.builtin.debug模块报告用户已被锁定。

请根据你的需求将your_target_host{{ user_name }}替换为实际值。

方案2 – 使用自定义脚本或模块

如果需要更灵活的控制或更复杂的操作,可以编写自定义脚本或模块来实现锁定用户的操作。这可能涉及到调用系统命令、处理返回结果等。

在这种情况下,你可以编写一个自定义的Ansible模块,或者在Playbook中使用command模块调用自定义脚本。这样可以确保满足你的特定需求,但可能需要更多的开发工作和测试。

方案3 – 使用shell模块

尽管不推荐使用shell模块,但如果你对系统命令有很好的控制,并且能够确保安全性和稳定性,你也可以使用shell模块来执行锁定用户的操作。但请注意,这可能会增加安全风险和复杂性。

方案4 – 附加资源

如果你想深入了解相关问题的讨论和解决方案,可以参考类似的问题和回答:Ansible, only disable existing users?

无论使用哪种方法,都请确保在实际操作之前进行测试,并在生产环境中谨慎操作,以防止意外情况和数据丢失。

希望这些解决方案能够帮助你实现通过给定用户名来锁定用户的需求。如有更多问题或疑虑,请随时提问。

正文完