-
Notifications
You must be signed in to change notification settings - Fork 1
/
gke_versions.go
122 lines (100 loc) · 2.5 KB
/
gke_versions.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
114
115
116
117
118
119
120
121
122
package gke_versions
import (
"context"
"encoding/json"
//"errors"
"github.com/pkg/errors"
"fmt"
"os"
"runtime"
"github.com/olekukonko/tablewriter"
"github.com/jessevdk/go-flags"
container "cloud.google.com/go/container/apiv1"
containerpb "google.golang.org/genproto/googleapis/container/v1"
)
const cmdName = "gke_versions"
// version by Makefile
var version string
// Required permissions
// - container.clusters.list
const googleApplicationCredentialsPath = "GOOGLE_APPLICATION_CREDENTIALS"
type cmdOpts struct {
Version bool `short:"v" long:"version" description:"show version"`
}
func printVersion() {
fmt.Printf(`%s %s
Compiler: %s %s
`,
cmdName,
version,
runtime.Compiler,
runtime.Version())
}
func getProjectName() (string, error) {
credentialFilePath := os.Getenv(googleApplicationCredentialsPath)
if credentialFilePath == "" {
return "", errors.New("GOOGLE_APPLICATION_CREDENTIALS is empty.\nSee also https://cloud.google.com/docs/authentication/getting-started#setting_the_environment_variable")
}
d, err := os.ReadFile(credentialFilePath)
if err != nil {
return "", err
}
type Credential struct {
ProjectId string `json:"project_id"`
}
var credential Credential
err = json.Unmarshal(d, &credential)
if err != nil {
return "", err
}
return credential.ProjectId, nil
}
func Run() error {
opts := cmdOpts{}
psr := flags.NewParser(&opts, flags.Default)
psr.Name = cmdName
_, err := psr.Parse()
if err != nil {
// TODO: handle err
return nil
}
if opts.Version {
printVersion()
return nil
}
projectName, err := getProjectName()
if err != nil {
return err
}
req := &containerpb.ListClustersRequest{
Parent: fmt.Sprintf("projects/%s/locations/-", projectName),
}
ctx := context.Background()
c, err := container.NewClusterManagerClient(ctx)
if err != nil {
return err
}
resp, err := c.ListClusters(ctx, req)
if err != nil {
return err
}
clusters := resp.Clusters
if len(clusters) == 0 {
fmt.Println("0 clusters")
return nil
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Cluster Name", "Cluster Version", "NodePool Name", "NodePool Version"})
table.SetAutoMergeCells(true)
table.SetAutoMergeCellsByColumnIndex([]int{0, 1})
table.SetRowLine(true)
var data [][]string
for _, cluster := range clusters {
for _, nodePool := range cluster.NodePools {
data = append(data, []string{cluster.Name, cluster.CurrentMasterVersion, nodePool.Name, nodePool.Version})
}
}
table.AppendBulk(data)
table.Render()
return nil
}