0

I want to start an ssh-agent instance when my user logs in. I also want several specific keys added to that agent after it has been created. I should be able to start and stop the agent through systemd. When I log out, that ssh-agent instance should be killed.

How would you write the systemd service file(s) to achieve this?

Lester Peabody
  • 2,359
  • 5
  • 17
  • 13
  • Related, not sure if this is a dupe: [How to start and use ssh-agent as systemd service?](https://unix.stackexchange.com/questions/339840) Can you have a look at it and tell us if that works for you? – Freddy Mar 04 '23 at 03:01
  • It's close to being a dupe, but I think the added requirement of adding the keys after start make this different enough. I actually figured it out and put my answer. – Lester Peabody Mar 04 '23 at 03:27

1 Answers1

1

The below worked for me.

After doing a lot of reading, re-reading, and then re-reading again, I found that ssh-agent can be run in the foreground, so systemd is able to manage it. In addition, I found you can add unlimited ExecStartPost directives, so I figured that would allow adding specific keys to the agent.

It worked wonderfully. The only oddity was that after stopping the service explicitly, it was in a failed state. More reading lead me to seeing that the ssh-agent process exits with a status of 2, so non-zero, so the SuccessExitStatus needed to be set to 2. Now, when stopped, its status shows as inactive as expected.

[Unit]
Description=Project SSH Agent

[Service]
Type=simple
Environment=PROJECT_SSH_AGENT=%t/project-ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a "$PROJECT_SSH_AGENT"
ExecStartPost=echo $SSH_AUTH_SOCK
ExecStartPost=echo $PROJECT_SSH_AGENT
ExecStartPost=/bin/sh -c "SSH_AUTH_SOCK=$PROJECT_SSH_AGENT /usr/bin/ssh-add /home/lpeabody/.ssh/id_rsa.project"
SuccessExitStatus=2

[Install]
WantedBy=default.target

Lester Peabody
  • 2,359
  • 5
  • 17
  • 13