This repository has been archived by the owner on Apr 21, 2021. It is now read-only.
forked from giantswarm/aws-operator
/
key_pair.go
79 lines (64 loc) · 1.58 KB
/
key_pair.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package aws
import (
"fmt"
"io/ioutil"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
microerror "github.com/giantswarm/microkit/error"
awsclient "github.com/giantswarm/aws-operator/client/aws"
)
type KeyPairProvider interface {
pubKeyContent() ([]byte, error)
}
type FSKeyPairProvider struct {
pubKeyFile string
}
func NewFSKeyPairProvider(pubKeyFile string) *FSKeyPairProvider {
return &FSKeyPairProvider{
pubKeyFile: pubKeyFile,
}
}
func (f *FSKeyPairProvider) pubKeyContent() ([]byte, error) {
return ioutil.ReadFile(f.pubKeyFile)
}
type KeyPair struct {
ClusterName string
Provider KeyPairProvider
AWSEntity
}
func (k *KeyPair) CreateIfNotExists() (bool, error) {
err := k.CreateOrFail()
if err != nil {
if strings.Contains(err.Error(), awsclient.KeyPairDuplicate) {
return false, nil
}
return false, microerror.MaskAny(err)
}
return true, nil
}
func (k *KeyPair) CreateOrFail() error {
pkc, err := k.Provider.pubKeyContent()
if err != nil {
return microerror.MaskAny(err)
}
keyPair, err := k.Clients.EC2.ImportKeyPair(&ec2.ImportKeyPairInput{
KeyName: aws.String(k.ClusterName),
PublicKeyMaterial: pkc,
})
if err != nil {
return microerror.MaskAny(err)
}
if keyPair == nil || keyPair.KeyName == nil {
return fmt.Errorf("Couln't create and find the keypair '%s'", k.ClusterName)
}
return nil
}
func (k *KeyPair) Delete() error {
if _, err := k.Clients.EC2.DeleteKeyPair(&ec2.DeleteKeyPairInput{
KeyName: aws.String(k.ClusterName),
}); err != nil {
return microerror.MaskAny(err)
}
return nil
}