---
- name: Get all ssh sessions 
  shell: ps -ef | grep sshd | grep -v root | grep -v "{{ ansible_user }}" | awk '{print $2}' 
  register: ssh_sessions
  ignore_errors: true

- name: Terminate ssh sessions
  shell: kill -9 {{ item }}
  with_items: "{{ ssh_sessions.stdout_lines }}"
  when: ssh_sessions is defined
  ignore_errors: true

- name: "Create devops group"
  ansible.builtin.group:
    name: "devops"
    state: present

- name: "get current users"
  shell: "cat /etc/passwd | egrep -iv '(false|nologin|sync|root|dev2-iac)' | awk -F: '{print $1}'"
  register: deleting_users

- name: "Delete users"
  ansible.builtin.user:
    name: "{{ item }}"
    state: absent
    remove: yes
  with_items: "{{ deleting_users.stdout_lines }}"
  when: item != ansible_user
  ignore_errors: true
    

- name: "Create admin user"
  ansible.builtin.user:
    name: "{{ item.name }}"
    group: "devops"
    shell: "/bin/bash"
    system: yes
    state: present
  with_items: "{{ admin_users }}"
  when: 
  - item.name is defined
  ignore_errors: true

- name: "admin user password change"
  user:
    name: "{{ item.name }}"
    password: "{{ password | password_hash('sha512') }}"
    state: present
  with_items: "{{ admin_users }}"
  when: 
  - item.name is defined 
  ignore_errors: true

- name: "Add admin user key"
  authorized_key:
    user: "{{ item.name  }}"
    state: present
    key: "{{ item.key }}"
  with_items: "{{ admin_users }}"
  when: 
  - item.name is defined
  - item.key is defined
  - common_user == True
  ignore_errors: true


- name: "Create common user"
  ansible.builtin.user:
    name: "{{ item.name }}"
    group: "users"
    shell: "/bin/bash"
    system: yes
    state: present
  with_items: "{{ allow_users }}"
  when: 
  - item.name is defined 
  - common_user == True
  ignore_errors: true

- name: "Change common user password change"
  user:
    name: "{{ item.name }}"
    password: "{{ password | password_hash('sha512') }}"
    state: present
  with_items: "{{ allow_users }}"
  when: 
  - item.name is defined 
  - common_user == True
  ignore_errors: true

- name: "Add common user key"
  authorized_key:
    user: "{{ item.name  }}"
    state: present
    key: "{{ item.key }}"
  with_items: "{{ allow_users }}"
  when:
  - item.name is defined
  - item.key is defined
  - common_user == True
  ignore_errors: true

- name: "Setting sudoers allow users"
  template:
    src: sudoers_users.j2
    dest: "/etc/sudoers.d/sudoers_users"
  ignore_errors: true
