Sunday, February 28, 2021

Ansible - Ad Hoc Commands

There are two ways of executing ansible commands and making configuration changes in the clients. First is executing ad hoc commands and the second is creating playbooks. In this blog post, we are going to demonstrate the use of ansible ad hoc commands.

Ad hoc commands are useful when we have to execute minor commands without creating playbooks. The syntax of ad hoc command is:

$ ansible <managed host> -m <module> -a 'arguments of the module'

The following example shows the use of ping module. We are pinging the ansible-clients group whose members are ansapp, ansdb and answeb. The ping is successful for all hosts.

 [devops@anscontrol ansible]$ ansible -m ping ansible-clients  
 ansapp | SUCCESS => {  
   "changed": false,  
   "ping": "pong"  
 }  
 ansdb | SUCCESS => {  
   "changed": false,  
   "ping": "pong"  
 }  
 answeb | SUCCESS => {  
   "changed": false,  
   "ping": "pong"  
 }  
The following example shows the use of user module. We have created the user named testuser5 with the shell /bin/false. The user is successfully created in the host ansapp.
 [devops@anscontrol ansible]$ ansible ansapp -m user -a 'name=testuser5 shell=/bin/false'  
 ansapp | SUCCESS => {  
   "changed": true,  
   "comment": "",  
   "createhome": true,  
   "group": 1002,  
   "home": "/home/testuser5",  
   "name": "testuser5",  
   "shell": "/bin/false",  
   "state": "present",  
   "system": false,  
   "uid": 1002  
The following example shows the use of the same user module. But this time we are deleting the above created user named testuser5. The user is successfully deleted in the host ansapp.
 [devops@anscontrol ansible]$ ansible ansapp -m user -a 'name=testuser5 state=absent remove=yes'  
 ansapp | SUCCESS => {  
   "changed": true,  
   "force": false,  
   "name": "testuser5",  
   "remove": true,  
   "state": "absent"  
 }  
The following example shows the use of yum module. We are installing the package named httpd using yum module on the ansible-clients hosts.
 [devops@anscontrol ansible]$ ansible ansible-clients -m yum -a 'name=httpd state=present'  
The following example shows the use of the same yum module. We are removing the package named httpd using yum module on the ansible-clients hosts.
 [devops@anscontrol ansible]$ ansible ansible-clients -m yum -a 'name=httpd state=absent'  

In the next blog posts we will demonstrate playbooks.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.