-
Notifications
You must be signed in to change notification settings - Fork 0
/
connector.go
49 lines (42 loc) · 1.39 KB
/
connector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package hetzner
import (
"context"
"fmt"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
"github.com/hetznercloud/hcloud-go/v2/hcloud/exp/kit/sshutil"
)
func (g *InstanceGroup) UploadSSHPublicKey(ctx context.Context, pub []byte) (sshKey *hcloud.SSHKey, err error) {
fingerprint, err := sshutil.GetPublicKeyFingerprint(pub)
if err != nil {
return nil, fmt.Errorf("could not get ssh key fingerprint: %w", err)
}
sshKey, _, err = g.client.SSHKey.GetByFingerprint(ctx, fingerprint)
if err != nil {
return nil, fmt.Errorf("could not get ssh key: %w", err)
}
if sshKey != nil {
g.log.Info("using existing ssh key", "name", sshKey.Name, "fingerprint", sshKey.Fingerprint)
return sshKey, nil
}
sshKey, _, err = g.client.SSHKey.GetByName(ctx, g.Name)
if err != nil {
return nil, fmt.Errorf("could not get ssh key: %w", err)
}
if sshKey != nil {
g.log.Warn("deleting existing ssh key", "name", sshKey.Name, "fingerprint", sshKey.Fingerprint)
_, err = g.client.SSHKey.Delete(ctx, sshKey)
if err != nil {
return nil, fmt.Errorf("could not delete ssh key: %w", err)
}
}
g.log.Info("uploading ssh key", "name", g.Name, "fingerprint", fingerprint)
sshKey, _, err = g.client.SSHKey.Create(ctx, hcloud.SSHKeyCreateOpts{
Name: g.Name,
Labels: g.labels,
PublicKey: string(pub),
})
if err != nil {
return nil, fmt.Errorf("could not upload ssh key: %w", err)
}
return sshKey, nil
}