---
- name: Deploy SSH keys
  ansible.posix.authorized_key:
    user: ansible
    key: "{{ item }}"
  loop: "{{ keys2deploy }}"
  when: keys2deploy is defined

- name: Allow sudo without password for ansible
  ansible.builtin.lineinfile:
    path: /etc/sudoers.d/95-lmn-ansible
    line: 'ansible ALL=(root) NOPASSWD: ALL'
    create: true
    owner: root
    group: root
    mode: '0700'

- name: Disable ansible user login
  ansible.builtin.user:
    name: ansible
    password_lock: true
  when: security_defaultuser_login_disable

- name: Limit SSH access to user ansible
  ansible.builtin.blockinfile:
    dest: /etc/ssh/sshd_config.d/local.conf
    create: true
    mode: '0644'
    block: |
      PasswordAuthentication no
      AllowUsers ansible
  notify: Reload sshd

- name: Deploy sudo configurations
  ansible.builtin.copy:
    dest: /etc/sudoers.d/90-lmn-security
    owner: root
    group: root
    mode: '0700'
    content: |
      {% for user, programs in sudo_permissions.items() %}
      {{ user }} ALL=(root) NOPASSWD: {% for program in programs %}{{ program }}{% if not loop.last %}, {% endif %}{% endfor %}
      {% endfor %}
  when: sudo_permissions is defined

- name: Deploy polkit configurations
  ansible.builtin.template:
    src: polkit_rules.j2
    dest: /etc/polkit-1/rules.d/lmn-security.rules
    mode: '0644'
  notify: Restart polkit
  when: polkit_rules is defined
