Ad hoc commands

Sometimes you want to execute a single command/task on the compute nodes. These single tasks are known as ad hoc commands in Ansible. In such commands, the option -m stands for module, without this option the default module to be executed is command. Arguments can be passed to the modules with the option -a. For instance, let’s execute the command hostname in all compute nodes at once:

[root@master ~]# ansible compute  -a 'hostname'
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
c03 | CHANGED | rc=0 >>
c01
c01 | CHANGED | rc=0 >>
c01
c02 | CHANGED | rc=0 >>
c02

This is an additional example with the module service, please see the playbook version here for the case of the httpd daemon:

[root@master ~]# ansible master  -m service -a "name=httpd state=started enabled=yes"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

dit_write cap_audit_control cap_setfcap cap_mac_override cap_mac_admin cap_syslog cap_wake_alarm cap_block_suspend cap_audit_read cap_perfmon cap_bpf",
      ...
      "WatchdogTimestampMonotonic": "85192268220",
      "WatchdogUSec": "0"
   }
}

Finally, another example with the module yum to install the package smartmontools:

[root@master ~]# ansible compute -o -m yum -a "name=smartmontools state=latest"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
c03 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": true,"msg": "","rc": 0,"results": ["Installed: smartmontools-1:7.1-3.el8.x86_64"]}
c02 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": true,"msg": "","rc": 0,"results": ["Installed: smartmontools-1:7.1-3.el8.x86_64"]}
c01 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": true,"msg": "","rc": 0,"results": ["Installed: smartmontools-1:7.1-3.el8.x86_64"]}

The option -o is used here to condense the output of the command.