Skip to content

Instantly share code, notes, and snippets.

@Chan9390
Created October 23, 2018 13:39
Show Gist options
  • Save Chan9390/efbed6be392b896e752b204d8480c342 to your computer and use it in GitHub Desktop.
Save Chan9390/efbed6be392b896e752b204d8480c342 to your computer and use it in GitHub Desktop.
Ansible script to manage Linux users and their authorized SSH keys
---
- hosts: production
gather_facts: no # This is helpful if a new EC2 instance is to be provisioned
become: yes
vars:
- default_users: ['nobody']
- required_users: ['badshah', 'bob', 'alice']
tasks:
- name: Check python
raw: test -e /usr/bin/python || (apt -y update && apt install -y python-minimal)
changed_when: false
- name: Get list of all users
shell: "getent passwd | awk -F: '$3 > 1000 {print $1}'"
changed_when: false
register: users
- name: Remove all users
user:
name: "{{ item }}"
state: absent
remove: yes
with_items: "{{ users.stdout_lines }}"
when: item not in default_users
- name: Add required users
user:
name: "{{ item }}"
state: present
with_items: "{{ required_users }}"
- name: Add SSH public keys
authorized_key:
user: "{{ item }}"
state: present
key: "{{ lookup('file', 'keys/{{ item }}') }}"
with_items: "{{ required_users }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment