Reputation: 935
I am writing an SSH config file and want to perform a bit of logic. For example:
Host myhost1
ProxyCommand ssh -A {choose randomly between [bastion_host1] and [bastion_host2]} -W %h:%p
Is it possible to achieve the above using (bash?) variables? Thanks!
Upvotes: 25
Views: 28120
Reputation: 124656
In ~/.ssh/config
you cannot have much logic, and no Bash. The manual for this file is in man ssh_config
, and it makes no mention of such feature.
What you can do is create a script that will have the logic you need, and make your ssh configuration call that script. Something along the lines of:
ProxyCommand ~/bin/ssh-randomly.sh [bastion_host1] [bastion_host2]
And write a Bash script ~/bin/ssh-randomly.sh
to take two hostname parameters, select one of them randomly, and run the real ssh
command with the appropriate parameters.
Upvotes: 10
Reputation: 71
This can be handled within ssh config by using a helper app. For example,
Host myhost match exec "randprog"
hostname host1
Host myhost
hostname host2
and then randprog
will randomly return 1 or 0 (0 will match the first line, giving host1).
Upvotes: 1
Reputation: 46856
Your ProxyCommand
can be a shell script.
host myhost1
ProxyCommand $HOME/bin/selecthost %h %p
And then in ~/bin/selecthost
:
#!/usr/bin/env bash
hosts=(bastion1 bastion2)
onehost=${hosts[$RANDOM % ${#hosts[@]}]}
ssh -x -a -q ${2:+-W $1:$2} $onehost
Untested. Your mileage may vary. May contain nuts.
Per comments, I've also tested the following, and it works nicely:
host myhost1 myhost2
ProxyCommand bash -c 'hosts=(bastion1 bastion2); ssh -xaqW%h:22 ${hosts[$RANDOM % ${#hosts[@]}]}'
Of course, this method doesn't allow you to specify a custom port per host. You could add that to the logic of a separate shell script if your SSH config matches multiple hosts in the same host
entry.
Upvotes: 17
Reputation: 531235
No; .ssh/config
is not processed by any outside program. You'll need a shell function along the lines of
ssh () {
(( $RANDOM % 2 )) && bastion=bastion_host1 || bastion=bastion_host2
command ssh -A "$bastion" "$@"
}
Upvotes: 7