Monday, 24 September 2018

Ansible user with pre-existing keys

This is the main task file:

---
- name: Create a login user with group
  user:
   name: '{{item.name}}'
   groups: '{{item.group}}'
   append: yes
   state: present
  when: item.group is defined
  with_items: '{{sshusers}}'

- name: Create a login user w/o group
  user:
   name: '{{item.name}}'
   state: present
  when: item.group is not defined
  with_items: '{{sshusers}}'

- name: Setting sudo permissions
  lineinfile:
   path: /etc/sudoers
   state: present
   regexp: '^%sudo'
   line: '%sudo ALL=(ALL) NOPASSWD: ALL'
   backrefs: yes

- name: Blocking root password access
  lineinfile:
   path: /etc/ssh/sshd_config
   state: present
   regexp: '^PermitRootLogin'
   line: 'PermitRootLogin without-password'
   backrefs: yes
  notify: reload ssh

- name: Creates directory
  file:
   path: /home/{{item.name}}/.ssh
   state: directory
   owner: '{{item.name}}'
   group: '{{item.name}}'
   mode: 0700
   recurse: yes
  with_items: '{{sshusers}}'

- name: ensure file exists
  copy:
   content: ""
   dest: /home/{{item.name}}/.ssh/authorized_keys
   force: no
   group: '{{item.name}}'
   owner: '{{item.name}}'
   mode: 0600
  with_items: '{{sshusers}}'

- name: copy SSH keys
  authorized_key:
   user: '{{item.name}}'
   key: "{{item.key}}"
   state: present
   exclusive: yes
  when: item.key is defined
  with_items: '{{sshusers}}'


The var file will look like this:

sshusers:
  - name: em_naveed
    group: sudo
    key: ssh-rsa AAAABxxxxxxxxxxxxxxxxx in clear text
  - name: em_hugo
    key: ssh-rsa AAAABxxxxxxxxxxxxxxxx in clear text


The handler file will look like this:

---
- name: reload ssh
  service:
   name: ssh
   state: reloaded

No comments:

Post a Comment