-
Notifications
You must be signed in to change notification settings - Fork 0
/
ycloud.go
73 lines (57 loc) · 1.41 KB
/
ycloud.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
package main
import (
"context"
"errors"
"os"
"github.com/yandex-cloud/go-genproto/yandex/cloud/compute/v1"
ycsdk "github.com/yandex-cloud/go-sdk"
iamkey "github.com/yandex-cloud/go-sdk/iamkey"
)
type Ycloud struct {
Sdk *ycsdk.SDK
}
type YcloudClient interface {
DeleteNode(string) error
}
func NewYcloudClient() (ycloud YcloudClient, err error) {
var sdk *ycsdk.SDK;
var credentials = os.Getenv("YANDEX_APPLICATION_CREDENTIALS")
if len(credentials) > 0 {
key, err := iamkey.ReadFromJSONFile(credentials)
if err != nil {
return nil, err
}
serviceAccount, err := ycsdk.ServiceAccountKey(key)
if err != nil {
return nil, err
}
sdk, err = ycsdk.Build(context.Background(), ycsdk.Config{
Credentials: serviceAccount,
})
} else {
sdk, err = ycsdk.Build(context.Background(), ycsdk.Config{
// Invoking InstanceServiceAccount automatically requests IAM token and uses
// it to generate SDK authorization credentials
Credentials: ycsdk.InstanceServiceAccount(),
})
}
if err != nil {
return nil, err
}
ycloud = &Ycloud{
Sdk: sdk,
}
return ycloud, nil
}
func (ycloud *Ycloud) DeleteNode(nodeId string) (err error) {
result, err := ycloud.Sdk.Compute().Instance().Delete(context.Background(), &compute.DeleteInstanceRequest{
InstanceId: nodeId,
})
if err != nil {
return err
}
if result.GetError() != nil {
return errors.New(result.GetError().Message)
}
return nil
}