Ansible - failed to lookup user

6.2k Views Asked by At

How can I solve problem with run ansible role below? If a user doesn't exist on the remote server, ansible gets me the error "Failed to lookup user test1: 'getpwnam(): name not found: test1". I need manage multiple users on multiple servers. Thanks

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

2

There are 2 best solutions below

1
On

I think, that I solved my problem.

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
0
On

Perhaps you could check the existing users through ansible's wrapper for getent? It feels a bit simpler and you don't need to use the shell module:

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()

Note though that as @techraf points out, at production environments you should always aim at declaring and knowing beforehand which users should and shouldn't be present :)