Bootstrap FreeKB - Ansible - Getting Started with the ansible ad hoc command
Ansible - Getting Started with the ansible ad hoc command

Updated:   |  Ansible articles

The ansible command can can be used to perform a single task against your control node (that's your Ansible server) or against one or more managed nodes (the target systems), whereas the ansible-playbook command is used to perform a series of tasks against managed nodes. Often, the ansible command is refered to as the ansible ad-hoc command, because it performs a single task.

The which command can be used to determine where the ansible command is located.

~]$ which ansible
/usr/local/bin/ansible

 

When first using the ansible ad hoc command, it's usually a good idea to ensure a command issued against your control node works as expected. The setup module can be used gather facts about the control node. Notice here that localhost is used, so that the command is run against the control node.

ansible localhost --module-name setup

 

Here is a snippet of some of the facts that could be returned.

"ansible_hostname": "server1"
"ansible_all_ip4v_addresses": "10.1.2.3"
"ansible_distribution": "CentOS"

 

Assuming the above command works as expected, almost always, the ping module is used as a basic test, to ping managed nodes. Let's say you have the following managed nodes defined in the default hosts file or your own inventory file.

windows:
  hosts:
    server1.example.com:
    server2.example.com:
linux:
  hosts:
    server3.example.com:
    server4.example.com:

 

Here is how you would use the ansible command to ping all of the managed nodes. 

ansible all --module-name ping 

 

Something like this should be returned.

server1.example.org | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
server2.example.org | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
server3.example.org | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
server4.example.org | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

 

The -a or --args option can be used to:

  • Invoke a native Linux command on managed nodes
  • Invoke a module on managed nodes

In this example, all managed nodes in your default hosts file or your own inventory file will be immediately restarted.

ansible all --args "/sbin/reboot now"

 

In this example, the yum module is used to update all managed nodes in your default hosts file or your own inventory file.

ansible all --module-name yum --args "name='*' state=latest"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 21ac30 in the box below so that we can be sure you are a human.