Configuring ssh-agent to work with sway and systemd
Recently I was setting up a Linux laptop where I mostly have no root access. I prefer i3 but since the distro I have to work with is shifting towards Wayland I decided to give Sway a try.
One aspect that required explicit configuration was ssh-agent.
Using X11 I would normally start ssh-agent before starting window manager. This way SSH_AUTH_SOCK environment variable in inherited by all processed started under window manager effectively pointing everything to the same agent. There're a few ways to start ssh-agent before the window manager. Some distributives will offer that by default and I prefer .xsession file.
However when GDM starts Sway it launches it more or less directly without any hooks to add custom configuration to.
Turns out the "correct" way to launch ssh-agent in this setup is to use systemd's user service and environment configuration. Arch has some great documentation (as always):
And I even found a user service on my system:
% systemctl --user list-unit-files ssh-agent.service
UNIT FILE STATE PRESET
ssh-agent.service static -
1 unit files listed.
However this service was configured in such a way that made it incompatible with setting environment variable via systemd - this service would not start ssh-agent when environment variable SSH_AUTH_SOCK is set. I ended up creating a new service by copying definition of ssh-agent.service from Arch linux:
% systemctl --user cat ssh-agent.service
# /usr/lib/systemd/user/ssh-agent.service
# Requires SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket" to be set in environment
[Unit]
ConditionEnvironment=!SSH_AGENT_PID
Description=OpenSSH key agent
Documentation=man:ssh-agent(1) man:ssh-add(1) man:ssh(1)
[Service]
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a ${SSH_AUTH_SOCK}
SuccessExitStatus=2
Type=simple
[Install]
WantedBy=default.target
In combination with .config/environment.d/000.ssh_auth_sock.conf
written as
SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/ssh-agent.socket"
I now have a working ssh-agent. All it took is configuration scattered over a couple of not immediately obvious files involving some mostly hidden interactions. It also requires that two parts of configuration refer to the same location of ssh-agent socket instead of setting once to the actually used value. Complexity of this approach is much higher while transparency and discoverability is much lower compared to the traditional approach of starting X11 graphical session.
I'm happy that FreeBSD, being my favourite OS, lets me stay away from systemd. Still once in a while I have to interact with it. So it makes sense to write down recipes for typical configuration tasks. It makes me feel sad how simple things are not at all simple in modern Linux.