Skip to content

Instantly share code, notes, and snippets.

@hmartiniano
Last active March 3, 2020 13:03
Show Gist options
  • Save hmartiniano/b0c88f4f25a793c827f096a52d872a86 to your computer and use it in GitHub Desktop.
Save hmartiniano/b0c88f4f25a793c827f096a52d872a86 to your computer and use it in GitHub Desktop.
Ansible playbook to create or remove users. Place SSH public keys in pub_keys/<username>.pub.
---
- hosts: all
user: root
vars:
users:
- username: data
groups: ""
shell: /bin/true
- username: "test"
groups: sudo, data, docker
- username: "test2"
groups: sudo, data, docker
- username: "test3"
groups: data, docker
remove_users:
- "test_user"
pre_tasks:
- name: install python
raw: test -e /usr/bin/python || (apt -qqy update && apt install -y python)
register: output
changed_when: output.stdout != ""
handlers:
- name: "Restart sshd"
service:
name: "sshd"
state: "restarted"
tasks:
- name: "Create user accounts"
user:
name: "{{ item.username }}"
groups: "{{ item.groups }}"
state: "present"
with_items: "{{ users }}"
- name: "Remove old user accounts in remove_users"
user:
name: "{{ item }}"
state: "absent"
with_items: "{{ remove_users }}"
- name: "Add authorized keys"
authorized_key:
user: "{{ item.username }}"
state: present
key: "{{ lookup('file', 'pub_keys/'+ item.username + '.pub') }}"
with_items: "{{ users }}"
- name: "Allow admin users to sudo without a password"
lineinfile:
dest: "/etc/sudoers" # path: in version 2.3
state: "present"
regexp: "^%admin"
line: "%admin ALL=(ALL) NOPASSWD: ALL"
- name: "Only SSH key-based root login via SSH"
lineinfile:
dest: "/etc/ssh/sshd_config"
regexp: "^PermitRootLogin"
line: "PermitRootLogin prohibit-password"
notify: "Restart sshd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment