Problem with authorized_keys with ansible

2.3k Views Asked by At

I am in the process of making knots in my brain concerning a concern for rights on the .ssh/authorized_keys.

I have my ansible script that works perfectly for creating my users on my servers and I just want to modify the rights of /home/user, /home/user/.ssh and finally /home/user.ssh/authorized_keys because they are not correct by default. I can't find where the problem is.

---
- hosts: all
  become: true
  tasks:
  - name: Creation groupe dev
    group:
      name: dev
      state: present

  - name: Creation des utilisateurs
    user:
      name: "{{ item.path }}"
      group: dev
      state: present
      password: "{{ lookup('password', '/dev/null') |password_hash('sha512') }}"
      update_password: on_create
    with_filetree: xx_pub_keys/

  - name: copie des clés SSH
    authorized_key:
      user: "{{ item.path }}"
      key: "{{ lookup('file', 'xx_pub_keys/' + item.path ) }}"
      state: present
    with_filetree: xx_pub_keys/

  - name: droits repertoires
    command:
      chmod go-w /home/{{ user.path }} && \
      chmod 700 /home/{{ user.path }} && \
      chmod 644 /home/{{ user.path }}/.ssh/authorized_keys

  - name: "Suppression des users eventuels"
    user:
      name: "{{ item.path }}"
      state: absent
      remove: true
    with_filetree: xx_pub_remove/

  - name: Allow admin users to sudo without a password
    lineinfile:
      dest: "/etc/sudoers"
      state: "present"
      regexp: "^%admin"
      line: "%admin ALL=(ALL) NOPASSWD: ALL"

  - name: restart sshd
    service: name=ssh state=restarted ...

So I tried in the "directory rights" section user.path, item.path, short item with with_items ... I have no idea ...

In short, I am in favor of any correction.

thank you in advance

1

There are 1 best solutions below

2
On BEST ANSWER

if i look on the task

  - name: droits repertoires
    command:
      chmod go-w /home/{{ user.path }} && \
      chmod 700 /home/{{ user.path }} && \
      chmod 644 /home/{{ user.path }}/.ssh/authorized_keys

it makes no sense to remove write-right from group other if you set the rights absolut later on to 700. In other words the first command is superfluous.

and then prefere always a module instead of a command if a module exist for that kind of task. So here you use the file module 2 times instead of command module:

  - name: "check or change /home/{{ user.path }}"
    file:
      path: /home/{{ user.path }}
      state: touch
      mode: '700'
  - name: "check or change /home/{{ user.path }}/.ssh/authorized_keys"
    file:
      path: /home/{{ user.path }}/.ssh/authorized_keys
      state: touch
      mode: '644'