-
Notifications
You must be signed in to change notification settings - Fork 18
/
options.go
402 lines (322 loc) · 11.4 KB
/
options.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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
SPDX-FileCopyrightText: 2021 SAP SE or an SAP affiliate company and Gardener contributors
SPDX-License-Identifier: Apache-2.0
*/
package providerenv
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/klog/v2"
clientgarden "github.com/gardener/gardenctl-v2/internal/client/garden"
"github.com/gardener/gardenctl-v2/internal/util"
"github.com/gardener/gardenctl-v2/pkg/ac"
"github.com/gardener/gardenctl-v2/pkg/cmd/base"
"github.com/gardener/gardenctl-v2/pkg/config"
"github.com/gardener/gardenctl-v2/pkg/env"
"github.com/gardener/gardenctl-v2/pkg/target"
)
type options struct {
base.Options
// Unset resets environment variables and configuration of the cloudprovider CLI for your shell.
Unset bool
// Shell to configure.
Shell string
// GardenDir is the configuration directory of gardenctl.
GardenDir string
// SessionDir is the session directory of gardenctl.
SessionDir string
// CmdPath is the path of the called command.
CmdPath string
// Target is the target used when executing the command
Target target.Target
// TargetFlags are the target override flags
TargetFlags target.TargetFlags
// Template is the script template
Template env.Template
// Force generates the script even if there are access restrictions to be confirmed
// Deprecated: Use ConfirmAccessRestriction instead
Force bool
// ConfirmAccessRestriction, when set to true, implies the user's understanding of the access restrictions for the targeted shoot.
// When set to false and access restrictions are present, the command will terminate with an error.
ConfirmAccessRestriction bool
}
// Complete adapts from the command line args to the data required.
func (o *options) Complete(f util.Factory, cmd *cobra.Command, _ []string) error {
ctx := f.Context()
logger := klog.FromContext(ctx)
if cmd.Name() != "provider-env" {
o.Shell = cmd.Name()
}
o.CmdPath = cmd.Parent().CommandPath()
o.GardenDir = f.GardenHomeDir()
o.Template = env.NewTemplate("helpers")
manager, err := f.Manager()
if err != nil {
return err
}
o.SessionDir = manager.SessionDir()
o.TargetFlags = f.TargetFlags()
if o.Force {
o.ConfirmAccessRestriction = true
logger.Info("The --force flag is deprecated and will be removed in a future gardenctl version. Please use the --confirm-access-restriction flag instead.")
}
return nil
}
// Validate validates the provided command options.
func (o *options) Validate() error {
if o.Shell == "" && o.Output == "" {
return pflag.ErrHelp
}
// Usually, we would check and return an error if both shell and output are set (not empty). However, this is not required because the output flag is not set for the shell subcommands.
if o.Shell != "" {
s := env.Shell(o.Shell)
return s.Validate()
}
return o.Options.Validate()
}
// AddFlags binds the command options to a given flagset.
func (o *options) AddFlags(flags *pflag.FlagSet) {
flags.BoolVarP(&o.Force, "force", "f", false, "Deprecated. Use --confirm-access-restriction instead. Generate the script even if there are access restrictions to be confirmed.")
flags.BoolVarP(&o.ConfirmAccessRestriction, "confirm-access-restriction", "y", o.ConfirmAccessRestriction, "Confirm any access restrictions. Set this flag only if you are completely aware of the access restrictions.")
flags.BoolVarP(&o.Unset, "unset", "u", o.Unset, fmt.Sprintf("Generate the script to unset the cloud provider CLI environment variables and logout for %s", o.Shell))
}
// Run does the actual work of the command.
func (o *options) Run(f util.Factory) error {
ctx := f.Context()
logger := klog.FromContext(ctx)
manager, err := f.Manager()
if err != nil {
return err
}
o.Target, err = manager.CurrentTarget()
if err != nil {
return err
}
if o.Target.GardenName() == "" {
return target.ErrNoGardenTargeted
}
client, err := manager.GardenClient(o.Target.GardenName())
if err != nil {
return fmt.Errorf("failed to create garden cluster client: %w", err)
}
if o.Target.ShootName() == "" && o.Target.SeedName() != "" {
shoot, err := client.GetShootOfManagedSeed(ctx, o.Target.SeedName())
if err != nil {
if apierrors.IsNotFound(err) {
return fmt.Errorf("cannot generate cloud provider CLI configuration script for non-managed seeds: %w", err)
}
return err
}
logger.V(1).Info("using referred shoot of managed seed",
"shoot", klog.ObjectRef{
Namespace: "garden",
Name: shoot.Name,
},
"seed", o.Target.SeedName())
o.Target = o.Target.WithProjectName("garden").WithShootName(shoot.Name)
}
if o.Target.ShootName() == "" {
return target.ErrNoShootTargeted
}
shoot, err := client.FindShoot(ctx, o.Target.AsListOption())
if err != nil {
return err
}
if shoot.Spec.SecretBindingName == nil || *shoot.Spec.SecretBindingName == "" {
return fmt.Errorf("shoot %q is not bound to a cloud provider secret", o.Target.ShootName())
}
secretBinding, err := client.GetSecretBinding(ctx, shoot.Namespace, *shoot.Spec.SecretBindingName)
if err != nil {
return err
}
secret, err := client.GetSecret(ctx, secretBinding.SecretRef.Namespace, secretBinding.SecretRef.Name)
if err != nil {
return err
}
cloudProfile, err := client.GetCloudProfile(ctx, shoot.Spec.CloudProfileName)
if err != nil {
return err
}
// check access restrictions
messages, err := o.checkAccessRestrictions(manager.Configuration(), o.Target.GardenName(), shoot)
if err != nil {
return err
}
return printProviderEnv(o, shoot, secret, cloudProfile, messages)
}
func printProviderEnv(o *options, shoot *gardencorev1beta1.Shoot, secret *corev1.Secret, cloudProfile *gardencorev1beta1.CloudProfile, messages ac.AccessRestrictionMessages) error {
providerType := shoot.Spec.Provider.Type
cli := getProviderCLI(providerType)
metadata := generateMetadata(o, cli)
if len(messages) > 0 {
if o.TargetFlags.ShootName() == "" || o.ConfirmAccessRestriction {
metadata["notification"] = messages.String()
} else {
if o.Output != "" {
return errors.New(
"the cloud provider CLI configuration script can only be generated if you confirm the access despite the existing restrictions. Use the --confirm-access-restriction flag to confirm the access",
)
}
s := env.Shell(o.Shell)
return o.Template.ExecuteTemplate(o.IOStreams.Out, "printf", map[string]interface{}{
"format": messages.String() + "\n%s %s\n%s\n",
"arguments": []string{
"The cloud provider CLI configuration script can only be generated if you confirm the access despite the existing restrictions.",
"Use the --confirm-access-restriction flag to confirm the access.",
s.Prompt(runtime.GOOS) + s.EvalCommand(fmt.Sprintf("%s --confirm-access-restriction %s", o.CmdPath, o.Shell)),
},
})
}
}
data, err := generateData(o, shoot, secret, cloudProfile, providerType, metadata)
if err != nil {
return err
}
if o.Output != "" {
return o.PrintObject(data)
}
return o.Template.ExecuteTemplate(o.IOStreams.Out, o.Shell, data)
}
func generateData(o *options, shoot *gardencorev1beta1.Shoot, secret *corev1.Secret, cloudProfile *gardencorev1beta1.CloudProfile, providerType string, metadata map[string]interface{}) (map[string]interface{}, error) {
data := map[string]interface{}{
"__meta": metadata,
"region": shoot.Spec.Region,
}
for key, value := range secret.Data {
data[key] = string(value)
}
switch providerType {
case "azure":
if !o.Unset {
configDir, err := createProviderConfigDir(o.SessionDir, providerType)
if err != nil {
return nil, err
}
data["configDir"] = configDir
}
case "gcp":
credentials := make(map[string]interface{})
serviceaccountJSON, err := parseGCPCredentials(secret, &credentials)
if err != nil {
return nil, err
}
if !o.Unset {
configDir, err := createProviderConfigDir(o.SessionDir, providerType)
if err != nil {
return nil, err
}
data["configDir"] = configDir
}
data["credentials"] = credentials
data["serviceaccount.json"] = string(serviceaccountJSON)
case "openstack":
authURL, err := getKeyStoneURL(cloudProfile, shoot.Spec.Region)
if err != nil {
return nil, err
}
data["authURL"] = authURL
_, ok := data["applicationCredentialSecret"]
if ok {
data["authType"] = "v3applicationcredential"
data["authStrategy"] = ""
data["tenantName"] = ""
data["username"] = ""
data["password"] = ""
} else {
data["authStrategy"] = "keystone"
data["authType"] = ""
data["applicationCredentialID"] = ""
data["applicationCredentialName"] = ""
data["applicationCredentialSecret"] = ""
}
}
filename := filepath.Join(o.GardenDir, "templates", providerType+".tmpl")
if err := o.Template.ParseFiles(filename); err != nil {
return nil, fmt.Errorf("failed to generate the cloud provider CLI configuration script: %w", err)
}
return data, nil
}
func generateMetadata(o *options, cli string) map[string]interface{} {
metadata := make(map[string]interface{})
metadata["unset"] = o.Unset
metadata["commandPath"] = o.CmdPath
metadata["cli"] = cli
metadata["targetFlags"] = getTargetFlags(o.Target)
if o.Shell != "" {
metadata["shell"] = o.Shell
metadata["prompt"] = env.Shell(o.Shell).Prompt(runtime.GOOS)
}
return metadata
}
func getProviderCLI(providerType string) string {
switch providerType {
case "alicloud":
return "aliyun"
case "gcp":
return "gcloud"
case "azure":
return "az"
default:
return providerType
}
}
func getTargetFlags(t target.Target) string {
if t.ProjectName() != "" {
return fmt.Sprintf("--garden %s --project %s --shoot %s", t.GardenName(), t.ProjectName(), t.ShootName())
}
return fmt.Sprintf("--garden %s --seed %s --shoot %s", t.GardenName(), t.SeedName(), t.ShootName())
}
func getKeyStoneURL(cloudProfile *gardencorev1beta1.CloudProfile, region string) (string, error) {
config, err := clientgarden.CloudProfile(*cloudProfile).GetOpenstackProviderConfig()
if err != nil {
return "", fmt.Errorf("failed to get openstack provider config: %w", err)
}
for _, keyStoneURL := range config.KeyStoneURLs {
if keyStoneURL.Region == region {
return keyStoneURL.URL, nil
}
}
if config.KeyStoneURL != "" {
return config.KeyStoneURL, nil
}
return "", fmt.Errorf("cannot find keystone URL for region %q in cloudprofile %q", region, cloudProfile.Name)
}
func parseGCPCredentials(secret *corev1.Secret, credentials interface{}) ([]byte, error) {
data := secret.Data["serviceaccount.json"]
if data == nil {
return nil, fmt.Errorf("no \"serviceaccount.json\" data in Secret %q", secret.Name)
}
if err := json.Unmarshal(data, credentials); err != nil {
return nil, err
}
return json.Marshal(credentials)
}
func createProviderConfigDir(sessionDir string, providerType string) (string, error) {
cli := getProviderCLI(providerType)
configDir := filepath.Join(sessionDir, ".config", cli)
err := os.MkdirAll(configDir, 0o700)
if err != nil {
return "", fmt.Errorf("failed to create %s configuration directory: %w", cli, err)
}
return configDir, nil
}
func (o *options) checkAccessRestrictions(cfg *config.Config, gardenName string, shoot *gardencorev1beta1.Shoot) (ac.AccessRestrictionMessages, error) {
if cfg == nil {
return nil, errors.New("garden configuration is required")
}
garden, err := cfg.Garden(gardenName)
if err != nil {
return nil, err
}
messages := ac.CheckAccessRestrictions(garden.AccessRestrictions, shoot)
return messages, nil
}