forked from kubernetes/kops
/
create_ig.go
113 lines (93 loc) · 2.27 KB
/
create_ig.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"bytes"
"fmt"
"os"
"github.com/spf13/cobra"
"k8s.io/kops/upup/pkg/api"
"k8s.io/kops/upup/pkg/fi/cloudup"
"k8s.io/kubernetes/pkg/kubectl/cmd/util/editor"
"path/filepath"
)
type CreateInstanceGroupCmd struct {
}
var createInstanceGroupCmd CreateInstanceGroupCmd
func init() {
cmd := &cobra.Command{
Use: "instancegroup",
Aliases: []string{"instancegroups", "ig"},
Short: "Create instancegroup",
Long: `Create an instancegroup configuration.`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
exitWithError(fmt.Errorf("Specify name of instance group to create"))
}
if len(args) != 1 {
exitWithError(fmt.Errorf("Can only create one instance group at a time!"))
}
err := createInstanceGroupCmd.Run(args[0])
if err != nil {
exitWithError(err)
}
},
}
createCmd.AddCommand(cmd)
}
func (c *CreateInstanceGroupCmd) Run(groupName string) error {
_, cluster, err := rootCommand.Cluster()
channel, err := cloudup.ChannelForCluster(cluster)
if err != nil {
return err
}
instanceGroupStore, err := rootCommand.InstanceGroupRegistry()
if err != nil {
return err
}
existing, err := instanceGroupStore.Find(groupName)
if err != nil {
return err
}
if existing != nil {
return fmt.Errorf("instance group %q already exists", groupName)
}
// Populate some defaults
ig := &api.InstanceGroup{}
ig.Name = groupName
ig.Spec.Role = api.InstanceGroupRoleNode
ig, err = cloudup.PopulateInstanceGroupSpec(cluster, ig, channel)
if err != nil {
return err
}
var (
edit = editor.NewDefaultEditor(editorEnvs)
)
raw, err := api.ToYaml(ig)
if err != nil {
return err
}
ext := "yaml"
// launch the editor
edited, file, err := edit.LaunchTempFile(fmt.Sprintf("%s-edit-", filepath.Base(os.Args[0])), ext, bytes.NewReader(raw))
defer func() {
if file != "" {
os.Remove(file)
}
}()
if err != nil {
return fmt.Errorf("error launching editor: %v", err)
}
group := &api.InstanceGroup{}
err = api.ParseYaml(edited, group)
if err != nil {
return fmt.Errorf("error parsing yaml: %v", err)
}
err = group.Validate(false)
if err != nil {
return err
}
err = instanceGroupStore.Create(group)
if err != nil {
return fmt.Errorf("error storing instancegroup: %v", err)
}
return nil
}