TIL how to run SSH tunnels in Bash scripts
To run a SSH tunnel in a Bash script or a CI job, we can utilize the following command:
ssh -o ExitOnForwardFailure=yes -f -L port:host:5432 user@$ip -i ~/.ssh/key.pub sleep 10
-
-o ExitOnForwardFailure
Specifies whether ssh should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh to exit if TCP connections to the ultimate forwarding destination fail.
-
-f
Requests ssh to go to background just before command execution. ... If the ExitOnForwardFailure configuration option is set to “yes”, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background.
-
-L port:host:5432 user@$ip
This opens an SSH tunnel via a jumphost.
-
sleep 10
With
-f
andsleep 10
, the SSH tunnel will attempt to close after 10 seconds. However, if the forwarded ports are still in use by another process, even after the 10 second period, the tunnel will remain open until the process exits.
# Use Cases
Some examples of use cases:
- Executing a long-running SQL query via a SSH tunnel in a CI job