This page looks best with JavaScript enabled

How to add ansible user to sudoers on remote servers using Bash script

 ·  ☕ 2 min read  ·  🐧 sysadmin
  1. Here is a video tutorial

Scripts and configuration files are available here:

  1. Install sshpass

SLES | openSUSE Leap 15.4

1
sudo zypper install sshpass 

Debian

1
sudo apt install sshpass 

Red Hat

1
sudo dnf install sshpass 
  1. Install sudo on remote hosts

SLES | openSUSE Leap 15.4

1
sudo zypper install sudo

Debian

1
sudo apt install sudo 

Red Hat

1
sudo dnf install sudo
  1. Type the below command:
1
visudo
  1. Change %sudo or %wheel to %admins

  2. Add the below line:

1
%admins  ALL=(ALL) NOPASSWD: ALL

Save and exit

  1. Add admins group
1
groupadd admins
  1. Create a file on a master server where you will install ansible in the future
1
vim pass_file

and place a password for the user that is currently able to connect to remote hosts.

  1. Make the script read only for this user
1
chmod 400 pass_file
  1. Create a list of servers with IP addresses or hostnames
1
vim servers
  1. Create a script
1
vim  ansible-sudo.sh

And add the below content

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/bin/bash
servers=$(cat servers)
echo -n "Enter the username: "
read userName
clear
for i in $servers; do
  sshpass -f pass_file ssh -q -t $USER@$i "hostname; sudo usermod -aG admins $userName"
done
echo
read -n1 -s -p "Checking? (y)es or (n)o " ans
echo
if [ $ans == 'y' ] ;then
  for i in $servers; do
    sshpass -f pass_file ssh -q -t $USER@$i "hostname; id $userName"
  done
fi
  1. Make sure that PasswordAuthentication has set boolean value to yes in /etc/ssh/sshd_config file on remote servers

  2. Make the script executable

1
chmod +x ansible-sudo.sh
  1. Execute the script
1
./ansible-sudo.sh
  1. Provide username: ansible

  2. See the result. User ansible should be added to group admins.

Share on

sysadmin
WRITTEN BY
sysadmin
QA & Linux Specialist