3

如何解决下面运行 ansible 角色的问题?如果远程服务器上不存在用户,ansible 会收到错误消息“无法查找用户 test1:'getpwnam(): name not found: test1”。我需要在多台服务器上管理多个用户。谢谢

vars:
user_list:
  - user: test1
    state: present
    path: /usr/local/test1/.ssh/authoried_keys
    keys:  
      - "ssh-rsa test1"
  - user: test2
    state: absent
    path: /home/test2/.ssh/authoried_keys
    keys:
      - "ssh-rsa test2"

tasks:
- name: Manage SSH-keys
  authorized_key:
    user: "{{ item.0.user }}"
    key: "{{ item.1 }}"
    path: "{{ item.0.path }}"
    state: "{{ item.0.state }}"
  with_subelements:
   - '{{ user_list }}'
   - keys

CentOS Linux 7、Ansible 2.4.2.0

4

2 回答 2

0

也许您可以通过 ansible 的包装器检查现有用户getent?感觉简单一点,不需要使用shell模块:

tasks:
      - name: Get existing users
        getent:
          database: passwd

      - name: Disable expired users
        user:
          name: "{{ item.name }}"
          shell: /sbin/nologin
        with_items:
          - "{{ users_removed }}"
        when: item.name in getent_passwd.keys()

请注意,正如@techraf 指出的那样,在生产环境中,您应该始终致力于事先声明和了解哪些用户应该和不应该出现:)

于 2021-12-02T12:39:37.323 回答
-2

我想,我解决了我的问题。

tasks:
- name: Check for users
  shell: cat /etc/passwd | cut -f1 -d":"
  register: sshkeys_users
  changed_when: False

- name: Manage SSH-keys
  authorized_key:
    user: "{{ item.0.user }}"
    key: "{{ item.1 }}"
    path: "{{ item.0.path }}"
    state: "{{ item.0.state }}"
  with_subelements:
    - '{{ user_list }}'
    - keys
  when: sshkeys_users is defined and item.0.user in sshkeys_users.stdout_lines
于 2018-01-17T16:21:52.297 回答