I would suggest to use Ansible ad hoc commands for this job. Ansible uses ssh and anyway it is a nice tool to manage multiple hosts, but now I am just focusing on the topic to run a single command on multiple hosts.
your user has an ssh key already installed on the remote hosts (and for most command you want passordless sudo rights there as well). So the following command should work without asking any password on any of your managed hosts (running
uptime command on the remote server):
ssh server1.mydomain.com uptime
or even better (to check passwordless sudo):
ssh server1.mydomain.com sudo uptime
As the ssh works fine you can create an inventory file for ansible:
inventory.yml (yes, it's in YAML format, so whitespace matters):
Run command on multiple hosts
and now run ansible to use
uptime command on
all of your hosts in the inventory:
ansible -i inventory.yml --one-line all -a uptime
server1.mydomain.com | CHANGED | rc=0 | (stdout) 14:48:24 up 5 days, 9:18, 1 user, load average: 0.16, 0.04, 0.01
server2.mydomain.com | CHANGED | rc=0 | (stdout) 12:48:24 up 6 days, 7:17, 3 users, load average: 0.02, 0.12, 0.17
server3.mydomain.com | CHANGED | rc=0 | (stdout) 14:48:24 up 5 days, 9:18, 1 user, load average: 0.08, 0.02, 0.01
--one-line option is not a must, just gives you nicer output if you have many servers and the output really just one line.
If the user on the remote server is not the same as your local user you can define that in the inventory or in the command line as well:
ansible -i inventory.yml -u remoteuser all -a uptime
If you need arguments for the command use quotation marks:
ansible -i inventory.yml all -a "ls -lh /etc"
And if you have to use pipe (
|) than you need the shell module:
ansible -i inventory.yml all -m shell -a "cat /etc/passwd | grep root"
And finally for the original question, use this command before ansible to accept any ssh host keys: