The purpose of this blog is to add a new user across all the manage nodes, make the user sudo, add ansible public key to the user so it can run ansible playbooks.

Example

cd /etc/ansible/playbooks
sudo nano create-new-user.yml

below creates the new user on all hosts

---
- hosts: all
  become: true
  tasks:
  - name: Create new user
    tags: always
    user:
      name: john
      group: root
ansible-playbook --ask-become-pass create-new-user.yml

now check if the user exists on the managed nodes

cd /home
ls
chage -l john

Now we will make the user john sudo, add ansible public key to the user so it can run ansible playbooks across all managed nodes. Modify the create-new-user.yml

sudo nano create-new-user.yml
---
- hosts: all
  become: true
  tasks:
  - name: Create new user
    tags: always
    user:
      name: john
      group: root

  - name: add ssh key for john
    tags: always
    authorized_key:
      user: john
      key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGCUJHlwNqf9Jk3kcZjBvHCxWd1/Fyv7RIEFWVw1Ux1v user@cnac.vmware.local"

  - name: add john to sudoers
    tags: always
    copy:
      src: /etc/ansible/files/sudoer_john
      dest: /etc/sudoers.d/john
      owner: root
      group: root
      mode: 0440

Now we will create the sudoers path /etc/ansible/files/sudoer_john on the control box

mkdir /etc/ansible/files
cd /etc/ansible/files
sudo nano sudoer_john

john ALL=(ALL) NOPASSWD:ALL
# On the managed node(s)
ls -l /etc/sudoers.d 
# shouldn't have john
ansible-playbook --ask-become-pass create-new-user.yml
# On the managed node(s)
ls -l /etc/sudoers.d 
# should have john now
# No password should be required to ssh to the managed node now
ssh john@ip 
# modify the ansible.cfg to allow john to be a remote users
sudo nano /etc/ansible/ansible.cfg
remote_user = john

the ansible playbook should be able to run as john and wont require –ask-become-pass as john is sudo on the managed nodes

ansible-playbook create-new-user.yml

Screen shots below

created new user

added sudo for john and ssh key for user

sudoer file added to control node

sudoer on managed node before and after

ssh not prompting for a password for john user

add ssh key to user and copying sudoer file to managed nodes

By Kad

Leave a Reply

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