Using systemd to start gpg-agent

gnupgsystemd

I've read up a little on systemd, but still can't quite figure out how to use it to automatically start gpg-agent on login. I gather I'd use systemctl --user, but constructing the gpg-agent.service has me stumped. Any and all pointers are welkcome.

Best Answer

The gpg-agent command starts a daemon, but programs that use it expect certain environment variables (GPG_AGENT_INFO and GPG_TTY) to be set so they know how to communicate with the agent. You have to somehow propagate these from the service script to your shells. The gpg-agent MAN page contains a snippet that starts the daemon and writes a shell code fragment to a file in the user's home

gpg-agent --daemon --write-env-file "${HOME}/.gpg-agent-info"

You can put this line into as shell script and call it from your service file

[Service]
Type=forking
ExecStart=script-file.sh
<...>

The .gpg-agent-info file has to be sourced from every shell. The MAN page recommends

if [ -f "${HOME}/.gpg-agent-info" ]; then
  . "${HOME}/.gpg-agent-info"
  export GPG_AGENT_INFO
fi

GPG_TTY=$(tty)
export GPG_TTY

in your .profile file to do this. Information on how to write systemd service files can be found in the systemd.service MAN page.

Related Question