Ansible: Running ad-hoc commands

Sometimes we want to run a single command on all of our servers. The ansible command allows us to easily do that.

Here’s a sample command:

sower --live ls '!noaccess' | xargs -P 10 -I {} bash -c 'echo "--- {} ---" && ssh root@{} /bin/true'
  • --inventory should point to the hosts.yml file in your seed inventory repository.
  • --one-line condenses the output to a single line making it easier to see which commands failed.
  • --forks indicates how many processes to run in paralell
  • --module-name shell indicates we are execute the “shell” module. The command module is the default if --module-name is not included. The command module allows you to execute one command, the shell modules is more flexable, allowing multiple commands and even shell syntax.
  • --args allows you to specify arguments for the chosen module.
  • '!noaccess' refers to either the single server name or the group you want to execute the command on. The ‘!’ negates the value. So, ‘!noaccess’ means run the command on all the servers in the inventory except the ones in the ’noaccess’ group. ‘Telehouse’ would run the command only on the servers in the Telehouse group.