BACK TO ARTICLES

Install Ansible on CentOS, Run Adhoc-Command, Create & Run Playbook – Step By Step Procedure

Published on August 24, 2020

Fakhar ul Hassan

Infrastructure Consultant, Cloud Architect & Automation, DevOps, Infrastructure as Code (IaC), Ansible, Terraform

Install Ansible on CentOS, Run Adhoc-Command, Create & Run Playbook – Step By Step Procedure

No alt text provided for this image

Preparing the Environment

a)- Three(3) CentOS machines

b)- A user (i.e. fakhar) should be created on all three machines

c)- IP addresses should be assigned, as per the provided figure above

d)- Internet connection should be available at control node (i.e. 192.168.0.150)

e)- Create a “test” folder on both managed hosts (i.e. 192.168.0.160 & 192.168.0.170) at path “/home/fakhar/”

On Ansible Control Node ( 192.168.0.150)

To Install Ansible on control node

Step-1: sudo yum install -y epel-release

No alt text provided for this image

Step-2: sudo yum install -y ansible

No alt text provided for this image

Step-3: sudo yum install -y tree (Optional)

No alt text provided for this image

To Generate and Copy SSH keys for Password-less Login

Note: A user named “fakhar” already exist on all three machines

Step-4: Generate ssh keys using command “ssh-keygen”

No alt text provided for this image

Step-5: Copy the ssh keys to target managed host using command “ssh-copy-id fakhar@192.168.0.160”

No alt text provided for this image

Step-6: Copy the ssh keys to target managed host using command “ssh-copy-id fakhar@192.168.0.170”

No alt text provided for this image

Create an Ansible inventory file

Step-7: Create an ansible inventory file, as shown below:

No alt text provided for this image

Create a PlayBook to Copy This Shell Script on Target Managed Hosts

Step-8: Create a playbook i.e. copyShellScript.yml

No alt text provided for this image

Create a simple shell script

Step-9: Create a simple shell script (i.e. showUserHostname.sh), For example:

No alt text provided for this image

How files are placed on Ansible Control Node? (Just to explain better)

No alt text provided for this image

Run Ansible Playbook to copy the shell script on target managed hosts

Step-10: Execute the following command to run the playbook:

[fakhar@CentOS-Ctrl-Node playbooks]$ ansible-playbook -i inventory copyShellScript.yml

No alt text provided for this image

Run Ansible Adhoc-Command to run the shell script on target managed hosts

Step-11: Execute the following command to run the playbook:

[fakhar@CentOS-Ctrl-Node playbooks]$ ansible all -i inventory -a “bash /home/fakhar/test/showUserHostname.sh”

No alt text provided for this image
Written by

Fakhar ul Hassan

Infrastructure Consultant, Cloud Architect & Automation, DevOps, Infrastructure as Code (IaC), Ansible, Terraform