Posted on Leave a comment

Create and manage users with Ansible – automatically create sudo users

Creating users is a very trivial task that requires time, especially if there is not a Active Directory mechanism integrated with the Linux servers. In order to make your life easier as an administrator you can run the below playbook that will create users based on a list and add them sudo capabilities.

Task 1
creates the users that have been specified on the loop section.

Task 2
creates the appropriate sudoers file

  1 ---               
  2 - name: create sudoers users based on request
  3   hosts: localhost
  4   become: true    
  5   tasks:          
  6     - name: create users based on a list
  7       user:       
  8         name: "{{ item }}"
  9         password: "{{ '#Passw0rd#' | password_hash('sha512') }}"
 10         shell: /bin/bash
 11       loop:       
 12         - user1
 13         - user2
 14                   
 15     - name: create sudoers file for user
 16       copy:       
 17         content: '{{ item }} ALL = (ALL) ALL'
 18         dest: "/etc/sudoers.d/{{item}}"
 19       loop:       
 20         - user1
 21         - user2

Run the playbook and verify that the password is correct and user has sudo capabilities.

ansible-playbook createusers.yml

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.