0

I have a simple bash script with an associative array called servers. The server name is the key and the IP address is the value. I use this when I want to run some one off script on all my servers.

for server in ${!servers[@]}; do
  echo ""
  echo -e "\e[93mConnecting to $server...\e[0m"
  ssh $user@${servers[$server]} 'sudo /bin/bash -s' < $1 | while read line; do echo -e "\e[92m[$server]\e[0m $line"; done
done

This works fine when I run it interactively and read from stdout but now I would like to run it automatically from cron and have the script that runs on the server conditionally send data to hipchat using curl.

Unfortunately many of the servers do not have meaningful hostnames set and I cant easily change the hostnames since there are decades old php websites on some of them that use the hostname to determine what environment they are running in and set db credentials ect... I do not want to audit dozens or even hundred+ websites for this.

Can I send the value of $server to the spawned bash shell on the server as an environment variable the script can use when sending messages to hipchat or email? I tried just doing SERVER=$server before /bin/bash but that did not seem to work.

digitaladdictions
  • 143
  • 1
  • 1
  • 8
  • 2
    Nothing set locally will affect the remote host. You'll need to set it in the session on the remote host (inside the `sudo`-run bash session more specifically). You can replace the `< $1` with something like `<(echo "SERVER=$server"; cat $1)` or something possibly. – Etan Reisner Jul 09 '15 at 23:21
  • It is odd to use `for server in ${!servers[@]}` to get the subscripts then refer to the values as `${servers[$server]}`. A more direct approach would be `for server in ${servers[@]}` then just refer to `$server`. – alvits Jul 10 '15 at 00:30
  • I am using both the key and the value though. ${servers[@]} would just expand to a list of IP addresses. I want to either output the name of the server if I an running it interactively or make the name of the server available as a env variable for the second script to reference for its reporting. As I stated I cant trust the hostname value on the servers or change them to something I can trust. I rather output a meaningful name than an IP address or at-least along with the IP address. – digitaladdictions Jul 10 '15 at 03:00

1 Answers1

0

I figured it out. I just had to remove the single quotes from around the call to the bash shell. Then adding SERVER=$server worked.

for server in ${!servers[@]}; do
  echo ""
  echo -e "\e[93mConnecting to $server...\e[0m"
  ssh $user@${servers[$server]} sudo SERVER=$server /bin/bash -s < $1 | while read line; do echo -e "\e[92m[$server]\e[0m $line"; done
done
digitaladdictions
  • 143
  • 1
  • 1
  • 8
  • Using double quotes there would be better than no quotes but yes, that's the general idea, do the assignment on the remote host. – Etan Reisner Jul 10 '15 at 03:25