Ansible,只禁用现有用户?

Ansible,只禁用现有用户?

我在 yaml 文件中有一个用户列表,带有一个标志:state。

如果标志未定义或者!=“不存在”,我将创建用户:

    - 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"

相反,我不允许“缺席”的用户连接:

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

但是我怎样才能做到只有现有用户才能被禁用?(而不是创建用户来将其 shell 设置为/sbin/nologin

答案1

问:“只能禁用现有用户。”

答:要仅修改当前用户,请使用盖特恩读取 /etc/passwd 并创建当前用户列表。然后在条件中使用它。例如

    - 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'

注 1:将状态默认为“存在”比测试属性是否存在更为可靠

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

注2:模块用户当“state=absent”时不会抱怨“name”不存在。因此,在这种情况下不需要测试用户的存在。只需禁用用户即可。例如

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

答案2

getent您可以使用with检查用户是否存在getent passwd {{ item }}

以下是剧本示例:

---
  - name: "Check if User exists sample"
    hosts: localhost
    connection: local
    vars:
      users:
        - nginx
        - root
        - user4
        - user3

    tasks:
      - name: "check for user in /etc/passwd"
        command: getent passwd {{ item }}
        register: check_user
        ignore_errors: yes 
        loop: "{{ users }}"
        register: all_checks
      
      - name: "iterate over checks"
        debug:
          msg:
          - "{{ item.rc }}"
          - "{{ item.item }}"
        when:
          - item.rc == 0
        loop: "{{ all_checks.results }}"

因此,在您的情况下,您需要修改您发布的剧本部分,如下所示:

tasks:
      - name: "check for user in /etc/passwd"
        command: getent passwd {{ item }}
        register: check_user
        ignore_errors: yes 
        loop: "{{ users }}"
        register: all_checks
      
      - name: "iterate over checks"
        user:
          name: "{{item.item}}"
          shell: "/sbin/nologin" 
        when:
          - item.state is defined and item.state == "absent"
          - item.rc == 0
        loop: "{{ all_checks.results }}"

相关内容