how to manage users with ansible

If you have multiple servers to manage, it can be a pain to manually add a new user, change a password, or lock an old account. Manually logging into all of your servers and performing these tasks is a real pain, and a huge waste of time.

Using ansible user module, you can manage users and ssh keys in a single run of playbook.

Create users

The home directory for the user will also be created by default. You have the option to choose your home directory by setting the home parameter.

Following playbook is for Red Hat/CentOS

You need to change user group for Debian based systems

authorize_users.yml

---
- hosts: tag_group_{{ env }}_webserver
  ignore_unreachable: true
  strategy: free
  gather_facts: False

  vars_files:
  - group_vars/all.yml

  vars:
    users:
      - tony
      - thor
      - hulk

  tasks:
  - name: Make sure we have a 'wheel' group
    group:
      name: wheel
      state: present
  - name: Allow 'wheel' group to have passwordless sudo
    lineinfile:
      dest: /etc/sudoers
      state: present
      regexp: '^%wheel'
      line: '%wheel ALL=(ALL) NOPASSWD: ALL'
      validate: visudo -cf %s
  - name: "Create user accounts and add users to groups"
    user:
      name: "{{ item }}"
      groups: "wheel"
      shell: /bin/bash
    loop: "{{ users }}"
  - name: Add sudoers users to wheel group
    user:
      name: "{{ item }}"
      groups: wheel
      append: yes
    loop: "{{ users }}"
  - name: "Add authorized keys"
    authorized_key:
      user: "{{ item }}"
      key: "{{ lookup('file', '~/.ssh/'+ item + '.pub') }}"
      state: present
    with_items: "{{ users }}"

Running:

“`$ ENV=prod; ansible-playbook   -i inventories/$ENV –extra-vars “env=$ENV” authorize_users.yml“`

Remove Users

Removing an existing user is easy. You just have to set the ‘state’ parameter to ‘absent’. It executes the ‘userdel’ command in the background.

deauthorize_users.yml

---
- hosts: tag_group_{{ env }}_webserver
  ignore_unreachable: true
  strategy: free
  gather_facts: False

  vars_files:
  - group_vars/all.yml

  vars:
    users:
      - frodo
      - sam
      - gollum

  tasks:
  - name: "Remove from authorized keys"
    authorized_key:
      user: "{{ item }}"
      key: "{{ lookup('file', '~/.ssh/lintel/'+ item + '.pub') }}"
      state: absent
    with_items: "{{ users }}"

  - name: "Remove from authorized keys from root"
    authorized_key:
      user: root
      key: "{{ lookup('file', '~/.ssh/lintel/'+ item + '.pub') }}"
      state: absent
    with_items: "{{ users }}"

  - name: Remove users
    user:
      name: "{{ item }}"
      remove: yes
      state: absent
    loop: "{{ users }}"

 

Running:

“`$ ENV=prod; ansible-playbook -i inventories/$ENV –extra-vars “env=$ENV” deauthorize_users.yml“`

Leave a Reply

Your email address will not be published. Required fields are marked *