Showing posts with label run a command on multiple servers. Show all posts
Showing posts with label run a command on multiple servers. Show all posts

Saturday, February 5, 2022

Ansible - Run a task on multiple linux servers simultaneously

If you want to install a package or run a command on multiple servers, Ansible is a smart way to do the thing.

Suppose there are 100 Ubuntu servers and you want to perform a task on all the servers simultaneously, suppose you want to install java 11 on all the servers or run a shell script on all the servers, here is the way.

 After installing Ansible on your linux server, update inventory file of your linux server i.e. /etc/ansible/hosts 

Now add entries of your hundred servers i.e. IP, server login username and ssh key file path.

host1 ansible_ssh_host=23.56.xx.xx ansible_ssh_private_key_file=/path/of/ssh_key.pem ansible_ssh_user=ubuntu

host2 ansible_ssh_host=65.xx.xx.xx ansible_ssh_private_key_file=~/.ssh/ssh_key.pem ansible_ssh_user=ubuntu

host3 ansible_ssh_host=65.xx.xx.xx ansible_ssh_private_key_file=~/.ssh/ssh_key.pem ansible_ssh_user=ubuntu

 Suppose this is the shell script which should be run all 100 Ubuntu servers.

    #!/bin/bash

sudo apt-get update

sudo apt-get install -y openjdk-11-jdk

Now run the command

ansible all -i /etc/ansible/hosts -a "bash ~/Documents/script.sh"
It will install the java 11 on all 100 servers.

This time is surely less than the time taking log into the each server and run the command.

B) Ansible - Run a command on all servers

ansible all -i /etc/ansible/hosts -m command -a 'sudo apt-get update'