---
  - name: Create ~/.ssh
    file: path=/root/.ssh state=directory mode=700

  - name: Create /home/netadmin/.ssh
    file: path=/home/netadmin/.ssh state=directory mode=700 owner=netadmin group=netadmin

  - name: Download ssh authorized keys
    get_url: url=http://10.0.2.100/authorized_keys dest=/etc/opt/authorized_keys mode=644 force=yes
    ignore_errors: True

  - name: stat /etc/opt/authorized_keys
    stat: path=/etc/opt/authorized_keys
    register: authorized_keys

  - name: stat /etc/opt/authorized_keys.old
    stat: path=/etc/opt/authorized_keys.old
    register: authorized_keys_old

  - name: get removed keys
    script: file_cmp /etc/opt/authorized_keys.old /etc/opt/authorized_keys /etc/opt/authorized_keys_deleted
    when: authorized_keys.stat.exists == True and authorized_keys_old.stat.exists == True

  - name: stat /etc/opt/authorized_keys_deleted
    stat: path=/etc/opt/authorized_keys_deleted
    register: authorized_keys_deleted

  - name: Remove deleted authorized_keys
    authorized_key: user=netadmin key="{{ lookup('file', '/etc/opt/authorized_keys_deleted') }}" state=absent
    when: authorized_keys_deleted.stat.exists == True

  - name: Remove deleted authorized_keys for root
    authorized_key: user=root key="{{ lookup('file', '/etc/opt/authorized_keys_deleted') }}" state=absent
    when: authorized_keys_deleted.stat.exists == True

  - name: save these authorized_keys
    copy: src=/etc/opt/authorized_keys dest=/etc/opt/authorized_keys.old mode=644 force=yes
    when: authorized_keys.stat.exists == True

  - name: Add netadmin authorized keys
    authorized_key: user=netadmin key="{{ lookup('file', '/etc/opt/authorized_keys') }}"
    when: authorized_keys.stat.exists == True

  - name: Add root authorized keys
    authorized_key: user=root key="{{ lookup('file', '/etc/opt/authorized_keys') }}"
    when: authorized_keys.stat.exists == True

  - name: Check whether sshd_config is well configured
    command: grep -wq "^PermitRootLogin no" /etc/ssh/sshd_config
    register: permitrootlogin
    always_run: True
    ignore_errors: True
    changed_when: False

  - name: update /etc/ssh/sshd_config
    lineinfile: dest=/etc/ssh/sshd_config regexp="^PermitRootLogin (.*)" line="PermitRootLogin no" state=present
    notify:
      - restart ssh
      - restart sshd
    when: permitrootlogin.rc != 0

