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?

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