Automatic SSH Agent in Arch Linux

This might not be needed

Before we get started; if you’re running WSL then this isn’t for you. If you’re running Gnome or KDE, then you can likely add the following to your ssh config and avoid the rest:

~/.ssh/config

Host *
    AddKeysToAgent yes

If you know for sure that you don’t have some kind of credential cacher going, then keep going.

Configuring ssh-agent in systemd

Huge thanks to lightsing on their StackOverflow answer. Make sure to updoot their post if this works for you.

Create the systemd folder for the user, then populate a service file with the required configuration.

mkdir -p ~/.config/systemd/user/
cat > ~/.config/systemd/user/ssh-agent.service << EOF
[Unit]
Description=SSH key agent

[Service]
Type=simple
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK

[Install]
WantedBy=default.target
EOF

Configure the environment variable to point to the ssh-agent socket:

mkdir -p ~/.config/environment.d/
cat > ~/.config/environment.d/ssh_auth_socket.conf << EOF 
SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/ssh-agent.socket"
EOF

Enable it to start on login, and start it right now:

systemctl --user enable --now ssh-agent

Merge the following entry into your SSH config:

Hosts *
    AddKeysToAgent yes

You’ll now see keys being auto-stored during your session. Logging in and out will cause you to need to re-enter your passphrases again.

[user@host ~]$ ssh somehost.com
Enter passphrase for key '/home/user/.ssh/keys/somekey': 
Last login: Tue Feb  7 19:34:46 2023 from 69.69.69.69
[user@somehost ~]$ logout
Connection to somehost.com closed.
[user@host ~]$ ssh somehost.com
Last login: Wed Jun 28 10:51:37 2023 from 69.69.69.69
[user@somehost ~]$ 

The above stopped working for me. Not too sure why.

Did the following from the Arch wiki:

cat > ~/.config/systemd/user/ssh-agent.service << EOF
[Unit]
Description=SSH key agent

[Service]
Type=simple
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
# DISPLAY required for ssh-askpass to work
Environment=DISPLAY=:0
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK

[Install]
WantedBy=default.target
EOF
cat > ~/.config/environment.d/ssh_auth_socket.conf << EOF
$XDG_RUNTIME_DIR/ssh-agent.socket
EOF
systemctl --user daemon-reload
systemctl --user restart ssh-agent

Following that, I was able to do a git pull. Leaving this here incase it helps someone.

[user@mymachine somedir]$ git pull
Enter passphrase for key '/home/user/.ssh/somekey': 
Already up to date.
[user@mymachine somedir]$ git pull
Already up to date.