Ssh – Proper way to send SSH commands to multiple clients with sudo

ssh

I have created a very simple shell script to send SSH commands to multiple hosts. Right now I have copied my ssh id so I don't have to use a password to login to the servers. But if I want to do a apt-get update for an example then I have to login as root and I am sure this isn't the preferred way to do this? So the question is what is the best way to send multiple ssh commands to multiple client's with sudo rights?

#!/bin/bash
# Hosts
hostarray=(
        "host1"
        "host2"
        "host3"
        )

for i in "${hostarray[@]}"; do
    ssh "$i" "command here"
done

Best Answer

As suggested above, Ansible can handle this more elegantly with the "--become --become-method=sudo --ask-become-password" options. However, you can, for example, put this in a file called /etc/sudoers.d/puppet (assuming your remote user is called puppet -- the naming is optional but it helps me keep things straight):

Defaults:puppet    !requiretty

puppet ALL=(ALL) NOPASSWD: ALL

This removes the need to type a password and the need for a tty.