-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathcreate.go
More file actions
288 lines (254 loc) · 11.5 KB
/
create.go
File metadata and controls
288 lines (254 loc) · 11.5 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package create
import (
"context"
"encoding/json"
"fmt"
"github.com/goccy/go-yaml"
"github.com/stackitcloud/stackit-cli/internal/cmd/params"
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
"github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/stackitcloud/stackit-cli/internal/pkg/examples"
"github.com/stackitcloud/stackit-cli/internal/pkg/flags"
"github.com/stackitcloud/stackit-cli/internal/pkg/globalflags"
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
"github.com/stackitcloud/stackit-cli/internal/pkg/services/ske/client"
skeUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/ske/utils"
"github.com/stackitcloud/stackit-cli/internal/pkg/utils"
"github.com/stackitcloud/stackit-cli/internal/pkg/validation"
"github.com/spf13/cobra"
"github.com/stackitcloud/stackit-sdk-go/services/ske"
)
const (
clusterNameArg = "CLUSTER_NAME"
disableWritingFlag = "disable-writing"
expirationFlag = "expiration"
filepathFlag = "filepath"
loginFlag = "login"
overwriteFlag = "overwrite"
)
type inputModel struct {
*globalflags.GlobalFlagModel
ClusterName string
DisableWriting bool
ExpirationTime *string
Filepath *string
Login bool
Overwrite bool
}
func NewCmd(params *params.CmdParams) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("create %s", clusterNameArg),
Short: "Creates or update a kubeconfig for a SKE cluster",
Long: fmt.Sprintf("%s\n\n%s\n%s\n%s\n%s",
"Creates a kubeconfig for a STACKIT Kubernetes Engine (SKE) cluster, if the config exists in the kubeconfig file the information will be updated.",
"By default, the kubeconfig information of the SKE cluster is merged into the default kubeconfig file of the current user. If the kubeconfig file doesn't exist, a new one will be created.",
"You can override this behavior by specifying a custom filepath using the --filepath flag or by setting the KUBECONFIG env variable (fallback).\n",
"An expiration time can be set for the kubeconfig. The expiration time is set in seconds(s), minutes(m), hours(h), days(d) or months(M). Default is 1h.\n",
"Note that the format is <value><unit>, e.g. 30d for 30 days and you can't combine units."),
Args: args.SingleArg(clusterNameArg, nil),
Example: examples.Build(
examples.NewExample(
`Create or update a kubeconfig for the SKE cluster with name "my-cluster. If the config exits in the kubeconfig file the information will be updated."`,
"$ stackit ske kubeconfig create my-cluster"),
examples.NewExample(
`Get a login kubeconfig for the SKE cluster with name "my-cluster". `+
"This kubeconfig does not contain any credentials and instead obtains valid credentials via the `stackit ske kubeconfig login` command.",
"$ stackit ske kubeconfig create my-cluster --login"),
examples.NewExample(
`Create a kubeconfig for the SKE cluster with name "my-cluster" and set the expiration time to 30 days. If the config exits in the kubeconfig file the information will be updated.`,
"$ stackit ske kubeconfig create my-cluster --expiration 30d"),
examples.NewExample(
`Create or update a kubeconfig for the SKE cluster with name "my-cluster" and set the expiration time to 2 months. If the config exits in the kubeconfig file the information will be updated.`,
"$ stackit ske kubeconfig create my-cluster --expiration 2M"),
examples.NewExample(
`Create or update a kubeconfig for the SKE cluster with name "my-cluster" in a custom filepath. If the config exits in the kubeconfig file the information will be updated.`,
"$ stackit ske kubeconfig create my-cluster --filepath /path/to/config"),
examples.NewExample(
`Get a kubeconfig for the SKE cluster with name "my-cluster" without writing it to a file and format the output as json`,
"$ stackit ske kubeconfig create my-cluster --disable-writing --output-format json"),
examples.NewExample(
`Create a kubeconfig for the SKE cluster with name "my-cluster. It will OVERWRITE your current kubeconfig file."`,
"$ stackit ske kubeconfig create my-cluster --overwrite true"),
),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
model, err := parseInput(params.Printer, cmd, args)
if err != nil {
return err
}
_, err = validation.ValidateAndGetProjectLabel(ctx, params.Printer, params.CliVersion, cmd, model.ProjectId)
if err != nil {
return err
}
// Configure API client
apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion)
if err != nil {
return err
}
if !model.AssumeYes && !model.DisableWriting {
var prompt string
if model.Overwrite {
prompt = fmt.Sprintf("Are you sure you want to create a kubeconfig for SKE cluster %q? This will OVERWRITE your current kubeconfig file, if it exists.", model.ClusterName)
} else {
prompt = fmt.Sprintf("Are you sure you want to update your kubeconfig for SKE cluster %q? This will update your kubeconfig file. \nIf it the kubeconfig file doesn't exists, it will create a new one.", model.ClusterName)
}
err = params.Printer.PromptForConfirmation(prompt)
if err != nil {
return err
}
}
// Call API
var (
kubeconfig string
respKubeconfig *ske.Kubeconfig
respLogin *ske.LoginKubeconfig
)
if !model.Login {
req, err := buildRequestCreate(ctx, model, apiClient)
if err != nil {
return fmt.Errorf("build kubeconfig create request: %w", err)
}
respKubeconfig, err = req.Execute()
if err != nil {
return fmt.Errorf("create kubeconfig for SKE cluster: %w", err)
}
if respKubeconfig.Kubeconfig == nil {
return fmt.Errorf("no kubeconfig returned from the API")
}
kubeconfig = *respKubeconfig.Kubeconfig
} else {
req, err := buildRequestLogin(ctx, model, apiClient)
if err != nil {
return fmt.Errorf("build login kubeconfig create request: %w", err)
}
respLogin, err = req.Execute()
if err != nil {
return fmt.Errorf("create login kubeconfig for SKE cluster: %w", err)
}
if respLogin.Kubeconfig == nil {
return fmt.Errorf("no login kubeconfig returned from the API")
}
kubeconfig = *respLogin.Kubeconfig
}
// Create the config file
var kubeconfigPath string
if model.Filepath == nil {
kubeconfigPath, err = skeUtils.GetDefaultKubeconfigPath()
if err != nil {
return fmt.Errorf("get default kubeconfig path: %w", err)
}
} else {
kubeconfigPath = *model.Filepath
}
if !model.DisableWriting {
if model.Overwrite {
err = skeUtils.WriteConfigFile(kubeconfigPath, kubeconfig)
} else {
err = skeUtils.MergeKubeConfig(kubeconfigPath, kubeconfig)
}
if err != nil {
return fmt.Errorf("write kubeconfig file: %w", err)
}
params.Printer.Outputf("\nSet kubectl context to %s with: kubectl config use-context %s\n", model.ClusterName, model.ClusterName)
}
return outputResult(params.Printer, model.OutputFormat, model.ClusterName, kubeconfigPath, respKubeconfig, respLogin)
},
}
configureFlags(cmd)
return cmd
}
func configureFlags(cmd *cobra.Command) {
cmd.Flags().Bool(disableWritingFlag, false, fmt.Sprintf("Disable the writing of kubeconfig. Set the output format to json or yaml using the --%s flag to display the kubeconfig.", globalflags.OutputFormatFlag))
cmd.Flags().BoolP(loginFlag, "l", false, "Create a login kubeconfig that obtains valid credentials via the STACKIT CLI. This flag is mutually exclusive with the expiration flag.")
cmd.Flags().String(filepathFlag, "", "Path to create the kubeconfig file. Will fall back to KUBECONFIG env variable if not set. In case both aren't set, the kubeconfig is created as file named 'config' in the .kube folder in the user's home directory.")
cmd.Flags().StringP(expirationFlag, "e", "", "Expiration time for the kubeconfig in seconds(s), minutes(m), hours(h), days(d) or months(M). Example: 30d. By default, expiration time is 1h")
cmd.Flags().Bool(overwriteFlag, false, "Overwrite the kubeconfig file.")
cmd.MarkFlagsMutuallyExclusive(loginFlag, expirationFlag)
}
func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) {
clusterName := inputArgs[0]
globalFlags := globalflags.Parse(p, cmd)
expTime := flags.FlagToStringPointer(p, cmd, expirationFlag)
if expTime != nil {
var err error
expTime, err = skeUtils.ConvertToSeconds(*expTime)
if err != nil {
return nil, &errors.FlagValidationError{
Flag: expirationFlag,
Details: err.Error(),
}
}
}
disableWriting := flags.FlagToBoolValue(p, cmd, disableWritingFlag)
isInvalidOutputFormat := globalFlags.OutputFormat == "" || globalFlags.OutputFormat == print.NoneOutputFormat || globalFlags.OutputFormat == print.PrettyOutputFormat
if disableWriting && isInvalidOutputFormat {
return nil, fmt.Errorf("when setting the flag --%s, you must specify --%s as one of the values: %s",
disableWritingFlag, globalflags.OutputFormatFlag, fmt.Sprintf("%s, %s", print.JSONOutputFormat, print.YAMLOutputFormat))
}
model := inputModel{
ClusterName: clusterName,
DisableWriting: disableWriting,
ExpirationTime: expTime,
Filepath: flags.FlagToStringPointer(p, cmd, filepathFlag),
GlobalFlagModel: globalFlags,
Login: flags.FlagToBoolValue(p, cmd, loginFlag),
Overwrite: flags.FlagToBoolValue(p, cmd, overwriteFlag),
}
if p.IsVerbosityDebug() {
modelStr, err := print.BuildDebugStrFromInputModel(model)
if err != nil {
p.Debug(print.ErrorLevel, "convert model to string for debugging: %v", err)
} else {
p.Debug(print.DebugLevel, "parsed input values: %s", modelStr)
}
}
return &model, nil
}
func buildRequestCreate(ctx context.Context, model *inputModel, apiClient *ske.APIClient) (ske.ApiCreateKubeconfigRequest, error) {
req := apiClient.CreateKubeconfig(ctx, model.ProjectId, model.Region, model.ClusterName)
payload := ske.CreateKubeconfigPayload{}
if model.ExpirationTime != nil {
payload.ExpirationSeconds = model.ExpirationTime
}
return req.CreateKubeconfigPayload(payload), nil
}
func buildRequestLogin(ctx context.Context, model *inputModel, apiClient *ske.APIClient) (ske.ApiGetLoginKubeconfigRequest, error) {
return apiClient.GetLoginKubeconfig(ctx, model.ProjectId, model.Region, model.ClusterName), nil
}
func outputResult(p *print.Printer, outputFormat, clusterName, kubeconfigPath string, respKubeconfig *ske.Kubeconfig, respLogin *ske.LoginKubeconfig) error {
switch outputFormat {
case print.JSONOutputFormat:
var err error
var details []byte
if respKubeconfig != nil {
details, err = json.MarshalIndent(respKubeconfig, "", " ")
} else if respLogin != nil {
details, err = json.MarshalIndent(respLogin, "", " ")
}
if err != nil {
return fmt.Errorf("marshal SKE Kubeconfig: %w", err)
}
p.Outputln(string(details))
return nil
case print.YAMLOutputFormat:
var err error
var details []byte
if respKubeconfig != nil {
details, err = yaml.MarshalWithOptions(respKubeconfig, yaml.IndentSequence(true), yaml.UseJSONMarshaler())
} else if respLogin != nil {
details, err = yaml.MarshalWithOptions(respLogin, yaml.IndentSequence(true), yaml.UseJSONMarshaler())
}
if err != nil {
return fmt.Errorf("marshal SKE Kubeconfig: %w", err)
}
p.Outputln(string(details))
return nil
default:
var expiration string
if respKubeconfig != nil {
expiration = fmt.Sprintf(", with expiration date %v (UTC)", utils.ConvertTimePToDateTimeString(respKubeconfig.ExpirationTimestamp))
}
p.Outputf("Updated kubeconfig file for cluster %s in %q%s\n", clusterName, kubeconfigPath, expiration)
return nil
}
}