Mahesh Rijal
Maheshrjl's Blog

Follow

Maheshrjl's Blog

Follow

A cheat sheet for Ansible Ad-Hoc commands

Mahesh Rijal's photo
Mahesh Rijal
·Jan 10, 2022·
A cheat sheet for Ansible Ad-Hoc commands

List of arguments for ad-hoc commands:

Ad-Hoc Syntax: ansible -i [inventory] [server group] -m [module] -u [user]

  • -m: Specify a module Eg: -m command -a ping

If module is not specified with -m ansible defaults to the command module for ad-hoc commands

  • -a: Give arguments for the specified module or command module by default.

Command module doesn't support | & redirection, use -m shell module

Eg: ansible all -m shell -a "command | grep text"

  • -f 1: Specify number of forks ansible uses. 1 will send command to one server at a time in order hosts are arranged in inventory.

  • -b: Becomes a different user root by default. --become is used to supplement sudo when not operating with Linux systems.

  • -K Will ask the password for root user when used with -b. Alternative:--ask-become-pass

  • --limit "ip1,ip2" Limits the host, command will not execute on the ip marked with limit. Also, supports regex for ip.

Polling & running in Background:

  • -p 0 Specify a polling time in seconds. Ansible will run the command in the background and check in the specified time if that command has executed.

  • 0 = polling disabled Below job runs for 30 minutes with polls every minute ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"

  • -B Specify time limit for the job to run in background. Below job runs for 3600 seconds without polling
    Eg: ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"

A result file is printed in output which gives a job ID. Check the result of the job using ansible all -m async_status -a "jid=jobid" Job ID is unique to each server.

Thanks for reading!