大网数据广告活动
服务器运维问答

Ansible, only disable existing users?

· 52CE 我爱测

I have a list of users in a yaml files, with a flag: state. If the flag is undefined or if it is != "absent", I create the user : - name: "create account for {{item.name}}" user: name: "{{item.name}}" create_home: no shell: "/bin…

问题原文

原帖链接 · Pierre-Antoine Guillaume · CC BY-SA 4.0

I have a list of users in a yaml files, with a flag: state.

If the flag is undefined or if it is != "absent", I create the user :

    - name: "create account for {{item.name}}"
      user:
        name: "{{item.name}}"
        create_home: no
        shell: "/bin/bash"
      loop: "{{users}}"
      when:
      - item.state is undefined or item.state != "absent"

and on the contrary, I disallow "absent" users to connect:

    - name: "disable user {{item.name}}"
      user:
        name: "{{item.name}}"
        shell: "/sbin/nologin"
      loop: "{{users}}"
      when:
        - item.state is defined and item.state == "absent"

But How can I make it so that only existing users can be disabled ? (And not creating a user to set its shell as /sbin/nologin)

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

Q: "Only existing users can be disabled."

A: To modify present users only, use getent to read /etc/passwd and create a list of present users. Then use it in the condition. For example

    - getent:
        database: passwd
    - set_fact:
        users_present: "{{ getent_passwd.keys()|list }}"

    - name: "disable user {{ item.name }}"
      user:
        name: "{{ item.name }}"
        shell: /sbin/nologin
      loop: "{{ users }}"
      when:
        - item.name in users_present
        - item.state|default('present') == 'absent'

Note1: It's more robust to default state to 'present' instead of testing the existence of the attribute

    - name: "create account for {{ item.name }}"
      user:
        name: "{{ item.name }}"
        create_home: no
        shell: /bin/bash
      loop: "{{ users }}"
      when: item.state|default('present') != 'absent'

Note2: The module user doesn't complain that a 'name' isn't present when 'state=absent'. Hence, it's not necessary to test the presence of a user in this case. Simply disable the user. For example

    - name: "disable user {{ item.name }}"
      user:
        name: "{{ item.name }}"
        state: absent
      loop: "{{ users }}"
      when: item.state|default('present') == 'absent'

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-09-28)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。