Ssh setup

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-04-24

Don't forget to update ssh_config for ssh agent forwarding

I wanted to pull a git repo from within an ansible script using the git@ syntax. This failed until I added an entry in ~/.ssh/config with ForwardAgent

Host somelocalidentifier
  HostName 12.127.44.13
  ForwardAgent yes

How to set default user for ssh

# ~/.ssh/config
Host somelocalidentifier
  HostName 12.127.44.13
  ForwardAgent yes
  User ubuntu

How to set per-server ssh key

# ~/.ssh/config
Host somelocalidentifier
  HostName 12.127.44.13
  ForwardAgent yes
  IdentityFile ~/.ssh/id_rsa

Sudo and SSH uses the wrong key

If you call ssh (or a command that relies on it, like git clone) with sudo in front, it looks for the keys in a folder like /home/root/.ssh/id_rsa. But you probably never stored your key there - instead it will reside somewhere like /home/$USERNAME/.ssh/id_rsa

It fails with ssh-forwarding, too. This is because sudo removes all environment variables of your normal user, including $SSH_AUTH_SOCK, which is how SSH forwarding gets its magic. One way around, however, is to edit /etc/sudoers using visudo and set the env_keep variable

Defaults    env_keep+=SSH_AUTH_SOCK

An even easier way is to tell sudo to bring the environment variables of the current user with it for that command:

sudo -E ssh git@github.com

If SSH fails to load a custom key, suspect file permissions

I had a file "gitsshwrapper":

key_file=tmp/code_diary_deploy_key

if [ ! -f "$key_file" ]; then
    echo "$key_file does not exist." 1>&2
    exit 1
fi
exec /usr/bin/ssh -vvv -i "$key_file" "$@"

It was called as follows:

GIT_SSH=./git_ssh_wrapper git clone git@github.com:jackkinsella/Code-Diary

It failed to find the repo, and the logs seemed to indicate that SSH could not find the key file (even though the wrapper file itself could, as proven by the early exit)

debug1: identity file /home/circleci/project/tmp/code_diary_deploy_key type -1
debug1: key_load_public: No such file or directory

In fact though, this log entry was misleading. It did find the private key successfully. It just didn't find a corresponding public one (which is fine, since it is optional here)

Ultimately to get it running on CircleCI, I needed to use sudo. This is presumably because the key is only present in the sudo user's home directory.

exec sudo /usr/bin/ssh -vvv -i "$key_file" "$@"