Home > Software design >  How to create user with Ansible correctly?
How to create user with Ansible correctly?

Time:10-30

I use this task to create new users on Linux

- name: Add user
  ansible.builtin.user:
    name: "{{ item.name }}"
    uid: "{{ item.uid }}"
    shell: /bin/bash
    group: "{{ item.group }}"
    groups: sshgroup
    append: yes
  with_items: "{{ users }}"

- name: Add .ssh directory
  file:
    path: "/home/{{ item.name }}/.ssh"
    state: directory
    mode: 0700
    owner: "{{ item.name }}"
    group: "{{ item.group }}"
  with_items: "{{ users }}"

- name: Add key
  lineinfile:
    dest: "/home/{{ item.name }}/.ssh/authorized_keys"
    state: present
    create: yes
    line: "{{ item.auth_key }}"
    owner: "{{ item.name }}"
    group: "{{ item.group }}"
    mode: 0600
  with_items: "{{ users }}"

Mostly the user can login via ssh successfully. But there was a case the new created user can't login with his/her private ssh key. They got a password request.

The users on the Linux like

$ ls -la /home/

# Can't login with ssh
drwxrwxr-x.  3 user1      user1     103 October 12 10:10 user1

# Can login with ssh
drwxr-xr-x.  7 user2      user2    4002 October 23 11:20 user2
drwx------.  3 user3      user3      80 October 21 12:00 user3

It seems they have different permissions. Why this caused? If change user1's permission, how to do with ansible?

CodePudding user response:

Are there alternate portions of the playbook or other users making modifications? Whether using ansible or any other method, users are typically created with a home directory permissions see to "drwx------." unless the folder already existed when creating the user or permissions were otherwise specified. If you want to ensure that it is always correct, you can always use an additional play like the following

- file:
    path: /home/{{ item.name }}/
    state: directory
    mode: 0700
    with_items: "{{ users }}"
  • Related