A quickie this time. I use Capistrano to deploy my Rails apps. There was a gem for Capistrano 2 that added an ssh command as in:
This would open an SSH connection to the production server and cd you to the current directory for the app. Super handy if you work on a lot of projects and don’t want remember what the server names and deploy paths for all of them.
The Capistrano 3 has a much different internal structure and the gem is long abandoned. Fortunately, it’s easy to recreate this functionality in a view lines of code.
Create lib/capistrano/tasks/ssh.rake and drop in:
1 2 3 4 5 6 7 8
The fiddly bits are the
cd && exec and the
-t makes sure we
have a terminal allocated on the server. Normally, when executing
commands (as opposed to starting a shell), a terminal isn’t needed,
but in this case we’re manually starting a shell, and we need it.
SSH, and then
cap, will exit when the remote command finish. If we
cd the command would login, change directory and then
finish. Exec-ing a shell after the
cd causes SSH to want for the
command, which will only finish when we log out. Exec-ing $SHELL
instead of hardcoding bash, given us some flexibility.
It’s a simple thing, but a nice time saver.
And for bonus points, the most common reason to open a shell to the server is to play around in the console. You can easily modify this task to do that with:
1 2 3 4 5 6 7 8
(You could append this to ssh.rake or create a separate console.rake.)
Note that when SSH is used to run a command, it does source your shell variables. If you use RVM or rbenv, you may need to manual set up you environment. For example, an RVM use might need:
Using ; instead of && will cause the cd and bundle to run even if the source fails, a quick and dirty way to make this work in cases where some servers are using RVM and some are not.