ssh-agent: autoload identities not already loaded (#7174)
With this PR the ssh-agent plugin checks the `ssh-add -l` output for the
identities added, and adds all those specified by the user that haven't been
added yet.
We also decouple the logic of starting ssh-agent from the logic of adding
identities, meaning that even if ssh-agent has been started by some other means
(like launchd) we can still ssh-add the user's identities.
Fixes #3019
Fixes #6979
Diff
1diff --git a/plugins/ssh-agent/ssh-agent.plugin.zsh b/plugins/ssh-agent/ssh-agent.plugin.zsh
2index fe4946c6d0000ae8d4a57a3f2fa399e01b62a964..a688855d06f86d2db3d2b883c54fb2706c29d0da 100644
3--- a/plugins/ssh-agent/ssh-agent.plugin.zsh
4+++ b/plugins/ssh-agent/ssh-agent.plugin.zsh
5@@ -2,20 +2,27 @@ typeset _agent_forwarding _ssh_env_cache
6 7 function _start_agent() {
8 local lifetime
9- local -a identities
10-
11- # start ssh-agent and setup environment
12 zstyle -s :omz:plugins:ssh-agent lifetime lifetime
1314+ # start ssh-agent and setup environment
15+ echo starting ssh-agent...
16 ssh-agent -s ${lifetime:+-t} ${lifetime} | sed 's/^echo/#echo/' >! $_ssh_env_cache
17 chmod 600 $_ssh_env_cache
18 . $_ssh_env_cache > /dev/null
19+}
2021- # load identies
22+function _add_identities() {
23+ local id line
24+ local -a identities ids
25 zstyle -a :omz:plugins:ssh-agent identities identities
2627- echo starting ssh-agent...
28- ssh-add $HOME/.ssh/${^identities}
29+ # get list of loaded identities
30+ for line in ${(f)"$(ssh-add -l)"}; do ids+=${${(z)line}[3]}; done
31+
32+ # add identities if not already loaded
33+ for id in ${^identities}; do
34+ [[ ${ids[(I)$HOME/.ssh/$id]} -le 0 ]] && ssh-add $HOME/.ssh/$id
35+ done
36 }
3738 # Get the filename to store/lookup the environment from
39@@ -42,6 +49,8 @@ else
40 _start_agent
41 fi
4243+_add_identities
44+
45 # tidy up after ourselves
46 unset _agent_forwarding _ssh_env_cache
47-unfunction _start_agent
48+unfunction _start_agent _add_identities