How to make gpg use the agent from `programs.gnupg.agent`

I am using NixOS and have set the option programs.gnupg.agent.enable = true. This generates two systemd user units: gpg-agent.service and gpg-agent.socket.

The socket unit provides /run/user/1000/gnupg/S.gpg-agent but I can not get gpg to use that socket. It always starts its own socket and thus does not run in the systemd service.

I started with this related question here on discourse, the linked commit about said option and the release notes for 20.03. It looks like gpg should pick the systemd socket but it does not and I have to use the other solution from these sources and install pinentry in my users.users.<user>.packages and specify the path in my gpg-agnet.conf file (because I do not want to use the default ncurses pinentry).

The result is that gpg uses its own socket, not managed by systemd, I have to install in my packages and the gpg-agent does not run in the generated systemd unit.

What am I doing wrong or how can I make gpg use the systemd socket generated by nix?
The alternative question would be: What is the use of the option programs.gnupg.agent.enable if the units can not be used?

NixOS is very good at configuring a system but is not meant to configure a user’s environment. For this, I strongly recommend home-manager which is also based on Nix and is dedicated to setting up a user environment.

I solved it using the following hack kaiser: enable gpg-agent · jtojnar/nixfiles@ebd6118 · GitHub.

@DamienCassou in this case I am asking why the option that is already provided by nixos (and it configures a systemd unit in user scope) does not work (as I would have it expected to work). So although your point might be valid I don’t see how it helps here.

@jtojnar there was a small note in that commit message to the rescue:

Unfortunately, when GNUPGHOME environment variable is set, gpg-agent uses a different socket directory, so the socket activation fails and gnupg starts the agent manually, without our overrides.
since the socket directory is based on a hash of the gnupg homedir.

As I had $GNUPGHOME set in my environment gpg was creating its own socket path. The quick and easy solution was to unset $GNUPGHOME and instead symlink ~/.gnupg to my directory of choice.

It’s not like NixOS is or can be consistent, it contains multitudes. Some people (like myself) want it to manage user environment.

And as you noticed, the option works as long as you do not set GNUPGHOME. Not much we can do about that until gnupg is fixed upstream. (See the issue linked in the commit message for more details.)