Skip to content

Commit 41a5a32

Browse files
Merge pull request #50 from am97/fix/issue49
Search for an existing key by fingerprint before attempting upload
2 parents eecb2b0 + 39c0838 commit 41a5a32

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

driver.go

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -241,14 +241,21 @@ func (d *Driver) Create() error {
241241
return errors.Wrap(err, "could not read ssh public key")
242242
}
243243

244-
keyopts := hcloud.SSHKeyCreateOpts{
245-
Name: d.GetMachineName(),
246-
PublicKey: string(buf),
247-
}
244+
key, err := d.getRemoteKeyWithSameFingerprint(buf)
245+
if key == nil {
246+
log.Infof("SSH key not found in Hetzner. Uploading...")
248247

249-
key, _, err := d.getClient().SSHKey.Create(context.Background(), keyopts)
250-
if err != nil {
251-
return errors.Wrap(err, "could not create ssh key")
248+
keyopts := hcloud.SSHKeyCreateOpts{
249+
Name: d.GetMachineName(),
250+
PublicKey: string(buf),
251+
}
252+
253+
key, _, err = d.getClient().SSHKey.Create(context.Background(), keyopts)
254+
if err != nil {
255+
return errors.Wrap(err, "could not create ssh key")
256+
}
257+
} else {
258+
log.Debugf("SSH key found in Hetzner. ID: %d", key.ID)
252259
}
253260

254261
d.KeyID = key.ID
@@ -606,6 +613,21 @@ func (d *Driver) getKey() (*hcloud.SSHKey, error) {
606613
return stype, nil
607614
}
608615

616+
func (d *Driver) getRemoteKeyWithSameFingerprint(pubkey_byte []byte) (*hcloud.SSHKey, error) {
617+
pubkey, _, _, _, err := ssh.ParseAuthorizedKey(pubkey_byte)
618+
if err != nil {
619+
return nil, errors.Wrap(err, "could not parse ssh public key")
620+
}
621+
622+
fp := ssh.FingerprintLegacyMD5(pubkey)
623+
624+
remotekey, _, err := d.getClient().SSHKey.GetByFingerprint(context.Background(), fp)
625+
if err != nil {
626+
return remotekey, errors.Wrap(err, "could not get sshkey by fingerprint")
627+
}
628+
return remotekey, nil
629+
}
630+
609631
func (d *Driver) getServerHandle() (*hcloud.Server, error) {
610632
if d.cachedServer != nil {
611633
return d.cachedServer, nil

0 commit comments

Comments
 (0)