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?

2
  • Related, not sure if this is a dupe: How to start and use ssh-agent as systemd service? Can you have a look at it and tell us if that works for you? Commented Mar 4, 2023 at 3: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. Commented Mar 4, 2023 at 3:27

1 Answer 1

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.