Automate SSH

2019, Oct 08    

I needed to use SSH as part of a gitlab CI job.

To properly secure the SSH connection, we cannot use tricks like -o StrictHostKeyChecking=no and we want to use keys (not passwords).

The solution is to give the users private key and the hosts public key to the CI job.

My solution is to put the private key as a variable, and the host public key as a file. The latter is outside my control and will probably not change often, the private key I would like to be able to update.

Start by creating the file ssh_host.pubkey using ssh-keygen:

ssh-keyscan -H <host_name> | tail -n 1 > ssh_host.pubkey

In the above example, I select the last entry if there are multiple. Feel free to add them all, or to grep on e.g. ecdsa.

Remember to add the file to the repository.

I put it in the before_scriptsection:

before_script:
- mkdir $HOME/.ssh -p
- cp ssh_host.pubkey $HOME/.ssh/known_hosts   
- echo "$SSH_PRIVATE_KEY" > $HOME/.ssh/id_rsa
- chmod 0600 $HOME/.ssh/id_rsa

id_rsa is convenient since it is one of the default identity files of openssh. Remember to change the _rsa part to match your key.

Also, naming it something non-default, forces you to specify it on every ssh command.