3

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

omfo
  • 39
  • 1
  • 4
  • 1
    And what is the expectation? Create user? Skip task? Silently ignore? – techraf Jan 17 '18 at 09:53
  • I want to run it on multiple servers and if a user doesn't exist do nothing on a server so skip the task. – omfo Jan 17 '18 at 10:03
  • That's not how you should manage the infrastructure. You should know (and declare) in advance what users exist. – techraf Jan 17 '18 at 10:10
  • On servers are many users, but I don't need to manage all users, but only specified users. For example: server1 - user1 - 3 ssh keys server2 - user2 - 3 ssh keys I need to add/remove specified ssh key to servers1-2 to users1-2. Can you help me, how can I do it? – omfo Jan 17 '18 at 11:30
  • So ensure the user accounts required for a specific server (not “all users”) are created before you add keys to their profiles. – techraf Jan 17 '18 at 12:36

2 Answers2

1

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

grubio
  • 11
  • 2
-2

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
omfo
  • 39
  • 1
  • 4