-
Notifications
You must be signed in to change notification settings - Fork 494
/
addcredential.go
720 lines (637 loc) · 22.8 KB
/
addcredential.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package cloud
import (
"fmt"
"io"
"io/ioutil"
"strings"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"gopkg.in/juju/names.v3"
apicloud "github.com/juju/juju/api/cloud"
jujucloud "github.com/juju/juju/cloud"
jujucmd "github.com/juju/juju/cmd"
"github.com/juju/juju/cmd/juju/common"
"github.com/juju/juju/cmd/juju/interact"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/environs"
"github.com/juju/juju/jujuclient"
)
var usageAddCredentialSummary = `
Adds a credential for a cloud to a local client and uploads it to a controller.`[1:]
var usageAddCredentialDetails = `
The juju add-credential command operates in two modes.
When called with only the <cloud name> argument, ` + "`juju add-credential`" + ` will
take you through an interactive prompt to add a credential specific to
the cloud provider.
Providing the ` + "`-f <credentials.yaml>` " + `option switches to the
non-interactive mode. <credentials.yaml> must be a path to a correctly
formatted YAML-formatted file.
Sample yaml file shows four credentials being stored against three clouds:
credentials:
aws:
<credential-name>:
auth-type: access-key
access-key: <key>
secret-key: <key>
azure:
<credential-name>:
auth-type: service-principal-secret
application-id: <uuid>
application-password: <password>
subscription-id: <uuid>
lxd:
<credential-name>:
auth-type: interactive
trust-password: <password>
<credential-name>:
auth-type: interactive
trust-password: <password>
The <credential-name> parameter of each credential is arbitrary, but must
be unique within each <cloud-name>. This allows allow each cloud to store
multiple credentials.
The format for a credential is cloud-specific. Thus, it's best to use
'add-credential' command in an interactive mode. This will result in
adding this new credential locally and / or uploading it to a controller
in a correct format for the desired cloud.
The ` + "`--replace`" + ` option is required if credential information
for the named cloud already exists locally. All such information will be
overwritten. This option is DEPRECATED, use 'juju update-credential' instead.
Examples:
juju add-credential google
juju add-credential google --local
juju add-credential google -c mycontroller
juju add-credential aws -f ~/credentials.yaml -c mycontroller
juju add-credential aws -f ~/credentials.yaml
juju add-credential aws -f ~/credentials.yaml --local
juju add-credential aws -f ~/credentials.yaml --no-prompt
Notes:
If you are setting up Juju for the first time, consider running
` + "`juju autoload-credentials`" + `. This may allow you to skip adding
credentials manually.
This command does not set default regions nor default credentials for the
cloud. The commands ` + "`juju default-region`" + ` and ` + "`juju default-credential`" + `
provide that functionality.
By default, after validating the contents, Juju will add a credential locally,
to the current client device, and will upload it to a controller.
If a current controller is detected, Juju will prompt the user to confirm
whether this new credential also needs to be uploaded.
Use --no-prompt option when this prompt is undesirable, but the upload to
the current controller is wanted.
Use --controller option to upload a credential to a different controller.
Use --local option to add credentials to the current device only.
Further help:
Please visit https://discourse.jujucharms.com/t/1508 for cloud-specific
instructions.
See also:
credentials
remove-credential
update-credential
default-credential
default-region
autoload-credentials
`
type addCredentialCommand struct {
modelcmd.OptionalControllerCommand
cloudByNameFunc func(string) (*jujucloud.Cloud, error)
// Replace, if true, existing credential information is overwritten.
Replace bool
// CloudName is the name of the cloud for which we add credentials.
CloudName string
// CredentialsFile is the name of the credentials YAML file.
CredentialsFile string
cloud *jujucloud.Cloud
// Region used to complete credentials' creation.
Region string
// These attributes are used when adding credentials to a controller.
remoteCloudFound bool
credentialAPIFunc func() (CredentialAPI, error)
// existsLocally whether this credential already exists locally.
existsLocally bool
}
// NewAddCredentialCommand returns a command to add credential information.
func NewAddCredentialCommand() cmd.Command {
store := jujuclient.NewFileClientStore()
c := &addCredentialCommand{
OptionalControllerCommand: modelcmd.OptionalControllerCommand{
Store: store,
},
cloudByNameFunc: jujucloud.CloudByName,
}
c.credentialAPIFunc = c.credentialsAPI
return modelcmd.WrapBase(c)
}
func (c *addCredentialCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "add-credential",
Args: "<cloud name>",
Purpose: usageAddCredentialSummary,
Doc: usageAddCredentialDetails,
})
}
func (c *addCredentialCommand) SetFlags(f *gnuflag.FlagSet) {
c.OptionalControllerCommand.SetFlags(f)
f.BoolVar(&c.Replace, "replace", false, "DEPRECATED: Overwrite existing credential information")
f.StringVar(&c.CredentialsFile, "f", "", "The YAML file containing credentials to add")
f.StringVar(&c.CredentialsFile, "file", "", "The YAML file containing credentials to add")
f.StringVar(&c.Region, "region", "", "Cloud region that credential is valid for")
}
func (c *addCredentialCommand) Init(args []string) (err error) {
if len(args) < 1 {
return errors.New("Usage: juju add-credential <cloud-name> [-f <credentials.yaml>]")
}
c.CloudName = args[0]
return cmd.CheckEmpty(args[1:])
}
func (c *addCredentialCommand) Run(ctxt *cmd.Context) error {
if c.Replace {
// TODO (anastasiamac 2019-07-10) --replace and everything related to it should be removed.
// https://bugs.launchpad.net/juju/+bug/1821279
ctxt.Warningf("--replace is DEPRECATED. Use 'juju update-credential' to update credentials.")
}
var err error
if !c.Local && c.ControllerName == "" {
// The user may have specified the controller via a --controller option.
// If not, let's see if there is a current controller that can be detected.
c.ControllerName, err = c.MaybePromptCurrentController(ctxt, "add a credential to")
if err != nil {
return errors.Trace(err)
}
}
// Check that the supplied cloud is valid.
if !c.Local && c.ControllerName != "" {
if err := c.maybeRemoteCloud(ctxt); err != nil {
if !errors.IsNotFound(err) {
logger.Errorf("%v", err)
}
ctxt.Infof("Cloud %q is not found on the controller, looking for a locally stored cloud.", c.CloudName)
}
}
if c.cloud == nil {
if c.cloud, err = common.CloudOrProvider(c.CloudName, c.cloudByNameFunc); err != nil {
logger.Errorf("%v", err)
ctxt.Infof("To view all available clouds, use 'juju clouds'.\nTo add new cloud, use 'juju add-cloud'.")
return cmd.ErrSilent
}
}
credentialsProvider, err := environs.Provider(c.cloud.Type)
if err != nil {
return errors.Annotate(err, "getting provider for cloud")
}
if len(c.cloud.AuthTypes) == 0 {
return errors.Errorf("cloud %q does not require credentials", c.CloudName)
}
schemas := credentialsProvider.CredentialSchemas()
existingCredentials, err := c.existingCredentialsForCloud()
if err != nil {
return errors.Trace(err)
}
if c.Region != "" {
if err := validCloudRegion(c.cloud, c.Region); err != nil {
return err
}
}
if c.CredentialsFile == "" {
return c.interactiveAddCredential(ctxt, schemas, existingCredentials)
}
if c.Region == "" {
c.Region = existingCredentials.DefaultRegion
}
data, err := ioutil.ReadFile(c.CredentialsFile)
if err != nil {
return errors.Annotate(err, "reading credentials file")
}
specifiedCredentials, err := jujucloud.ParseCredentials(data)
if err != nil {
return errors.Annotate(err, "parsing credentials file")
}
credentials, ok := specifiedCredentials[c.CloudName]
if !ok {
return errors.Errorf("no credentials for cloud %s exist in file %s", c.CloudName, c.CredentialsFile)
}
// We could get a duplicate "interactive" entry for the validAuthType() call,
// however it doesn't matter for the validation, so just add it.
authTypeNames := c.cloud.AuthTypes
if _, ok := schemas[jujucloud.InteractiveAuthType]; ok {
authTypeNames = append(authTypeNames, jujucloud.InteractiveAuthType)
}
validAuthType := func(authType jujucloud.AuthType) bool {
for _, authT := range authTypeNames {
if authT == authType {
return true
}
}
return false
}
provider, err := environs.Provider(c.cloud.Type)
if err != nil {
return errors.Trace(err)
}
var allNames []string
added := map[string]jujucloud.Credential{}
for name, cred := range credentials.AuthCredentials {
if !names.IsValidCloudCredentialName(name) {
return errors.Errorf("%q is not a valid credential name", name)
}
if !validAuthType(cred.AuthType()) {
return errors.Errorf("credential %q contains invalid auth type %q, valid auth types for cloud %q are %v", name, cred.AuthType(), c.CloudName, c.cloud.AuthTypes)
}
// When in non-interactive mode we still sometimes want to finalize a
// cloud, so that we can either validate the credentials work before a
// bootstrap happens or improve security models, where by we remove any
// shared/secret passwords (lxd remote security).
// This is optional and is backwards compatible with other providers.
if shouldFinalizeCredential(provider, cred) {
newCredential, err := finalizeProvider(ctxt, c.cloud, c.Region, existingCredentials.DefaultRegion, cred.AuthType(), cred.Attributes())
if err != nil {
return errors.Errorf("Could not verify credential %v for cloud %v locally: %v", name, c.CloudName, err)
}
cred = *newCredential
}
added[name] = cred
if _, ok := existingCredentials.AuthCredentials[name]; ok {
ctxt.Warningf("credential %q for cloud %q already exists locally, use 'juju update-credential %v %v -f %v' to update this local client copy", name, c.CloudName, c.CloudName, name, c.CredentialsFile)
continue
}
existingCredentials.AuthCredentials[name] = cred
allNames = append(allNames, name)
}
return c.internalAddCredential(ctxt, "added", *existingCredentials, added, allNames)
}
func (c *addCredentialCommand) internalAddCredential(ctxt *cmd.Context, verb string, existingCredentials jujucloud.CloudCredential, added map[string]jujucloud.Credential, allNames []string) error {
var err error
// Local processing.
if len(allNames) == 0 {
fmt.Fprintf(ctxt.Stdout, "No local credentials for cloud %q changed.\n", c.CloudName)
} else {
var msg string
if len(allNames) == 1 {
msg = fmt.Sprintf(" %q", allNames[0])
} else {
msg = fmt.Sprintf("s %q", strings.Join(allNames, ", "))
}
err = c.Store.UpdateCredential(c.CloudName, existingCredentials)
if err == nil {
fmt.Fprintf(ctxt.Stdout, "Credential%s %s locally for cloud %q.\n\n", msg, verb, c.CloudName)
} else {
fmt.Fprintf(ctxt.Stdout, "Credential%s not %v locally for cloud %q: %v\n\n", msg, verb, c.CloudName, err)
err = cmd.ErrSilent
}
}
// Remote processing.
if !c.Local {
if c.ControllerName != "" {
return c.addRemoteCredentials(ctxt, added, err)
} else {
ctxt.Infof("There are no controllers specified - not adding a credential to any controller.")
return err
}
}
return err
}
func (c *addCredentialCommand) existingCredentialsForCloud() (*jujucloud.CloudCredential, error) {
existingCredentials, err := c.Store.CredentialForCloud(c.CloudName)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Annotate(err, "reading existing credentials for cloud")
}
if errors.IsNotFound(err) {
existingCredentials = &jujucloud.CloudCredential{
AuthCredentials: make(map[string]jujucloud.Credential),
}
}
return existingCredentials, nil
}
func (c *addCredentialCommand) interactiveAddCredential(ctxt *cmd.Context, schemas map[jujucloud.AuthType]jujucloud.CredentialSchema, existingCredentials *jujucloud.CloudCredential) error {
errout := interact.NewErrWriter(ctxt.Stdout)
pollster := interact.New(ctxt.Stdin, ctxt.Stdout, errout)
credentialName, err := c.promptCredentialName(pollster, ctxt.Stdout)
if err != nil {
return err
}
verb := "added"
if _, ok := existingCredentials.AuthCredentials[credentialName]; ok {
fmt.Fprint(ctxt.Stdout, fmt.Sprintf("A credential %q already exists locally on this client.\n", credentialName))
overwrite, err := pollster.YN("Replace local credential", false)
if err != nil {
return errors.Trace(err)
}
if !overwrite {
return nil
}
verb = "updated"
}
authTypeNames := c.cloud.AuthTypes
// Check the credential schema for "interactive", add to list of
// possible authTypes for add-credential
if _, ok := schemas[jujucloud.InteractiveAuthType]; ok {
foundIt := false
for _, name := range authTypeNames {
if name == jujucloud.InteractiveAuthType {
foundIt = true
}
}
if !foundIt {
authTypeNames = append(authTypeNames, jujucloud.InteractiveAuthType)
}
}
err = c.promptCloudRegion(pollster, existingCredentials, ctxt.Stdout)
if err != nil {
return errors.Trace(err)
}
authType, err := c.promptAuthType(pollster, authTypeNames, ctxt.Stdout)
if err != nil {
return errors.Trace(err)
}
schema, ok := schemas[authType]
if !ok {
return errors.NotSupportedf("auth type %q for cloud %q", authType, c.CloudName)
}
attrs, err := c.promptCredentialAttributes(pollster, authType, schema)
if err != nil {
return errors.Trace(err)
}
newCredential, err := finalizeProvider(ctxt, c.cloud, c.Region, existingCredentials.DefaultRegion, authType, attrs)
if err != nil {
return errors.Trace(err)
}
existingCredentials.AuthCredentials[credentialName] = *newCredential
return c.internalAddCredential(ctxt, verb, *existingCredentials, map[string]jujucloud.Credential{credentialName: *newCredential}, []string{credentialName})
}
func finalizeProvider(ctxt *cmd.Context, cloud *jujucloud.Cloud, regionName, defaultRegion string, authType jujucloud.AuthType, attrs map[string]string) (*jujucloud.Credential, error) {
cloudEndpoint := cloud.Endpoint
cloudStorageEndpoint := cloud.StorageEndpoint
cloudIdentityEndpoint := cloud.IdentityEndpoint
if len(cloud.Regions) > 0 {
// For some providers we must have a region to construct a valid credential, for e.g. azure.
// If a region was specified by the user, we'd use it;
// otherwise, we'd use default region if one is set or, if not, the first region.
if regionName == "" {
regionName = defaultRegion
}
region := cloud.Regions[0]
if regionName != "" {
for _, r := range cloud.Regions {
if r.Name == regionName {
region = r
}
}
}
cloudEndpoint = region.Endpoint
cloudStorageEndpoint = region.StorageEndpoint
cloudIdentityEndpoint = region.IdentityEndpoint
}
credentialsProvider, err := environs.Provider(cloud.Type)
if err != nil {
return nil, errors.Trace(err)
}
newCredential, err := credentialsProvider.FinalizeCredential(
ctxt, environs.FinalizeCredentialParams{
Credential: jujucloud.NewCredential(authType, attrs),
CloudEndpoint: cloudEndpoint,
CloudStorageEndpoint: cloudStorageEndpoint,
CloudIdentityEndpoint: cloudIdentityEndpoint,
},
)
return newCredential, errors.Annotate(err, "finalizing credential")
}
func (c *addCredentialCommand) promptCredentialName(p *interact.Pollster, out io.Writer) (string, error) {
credentialName, err := p.EnterVerify("credential name", func(value string) (ok bool, errmsg string, err error) {
if !names.IsValidCloudCredentialName(value) {
return false, fmt.Sprintf("Invalid credential name: %q", value), nil
}
return true, "", nil
})
if err != nil {
return "", errors.Trace(err)
}
return credentialName, nil
}
func (c *addCredentialCommand) promptCloudRegion(p *interact.Pollster, existingCredentials *jujucloud.CloudCredential, out io.Writer) error {
regions := c.cloud.Regions
if len(regions) == 0 {
return nil
}
if c.Region != "" {
fmt.Fprintf(out, "User specified region %q, using it.\n\n", c.Region)
return nil
}
choices := make([]string, len(regions))
for i, r := range regions {
choices[i] = r.Name
}
def := "any region, credential is not region specific"
var err error
c.Region, err = p.SelectVerify(interact.List{
Singular: "region",
Plural: "regions",
Options: choices,
Default: def,
}, func(value string) (ok bool, errmsg string, err error) {
if value == "" {
return true, "", nil
}
if regionErr := validCloudRegion(c.cloud, value); regionErr != nil {
return false, regionErr.Error(), nil
}
return true, "", nil
})
if c.Region == def {
c.Region = ""
}
return errors.Trace(err)
}
func (c *addCredentialCommand) promptAuthType(p *interact.Pollster, authTypes []jujucloud.AuthType, out io.Writer) (jujucloud.AuthType, error) {
if len(authTypes) == 1 {
fmt.Fprintf(out, "Using auth-type %q.\n\n", authTypes[0])
return authTypes[0], nil
}
choices := make([]string, len(authTypes))
for i, a := range authTypes {
choices[i] = string(a)
}
// If "interactive" is a valid credential type, choose by default
// o.w. take the top of the slice
def := string(jujucloud.InteractiveAuthType)
if !strings.Contains(strings.Join(choices, " "), def) {
def = choices[0]
}
authType, err := p.Select(interact.List{
Singular: "auth type",
Plural: "auth types",
Options: choices,
Default: def,
})
if err != nil {
return "", errors.Trace(err)
}
return jujucloud.AuthType(authType), nil
}
func (c *addCredentialCommand) promptCredentialAttributes(p *interact.Pollster, authType jujucloud.AuthType, schema jujucloud.CredentialSchema) (attributes map[string]string, err error) {
// Interactive add does not support adding multi-line values, which
// is what we typically get when the attribute can come from a file.
// For now we'll skip, and just get the user to enter the file path.
// TODO(wallyworld) - add support for multi-line entry
attrs := make(map[string]string)
for _, attr := range schema {
currentAttr := attr
value := ""
var err error
if currentAttr.FileAttr == "" {
value, err = c.promptFieldValue(p, currentAttr)
if err != nil {
return nil, err
}
} else {
currentAttr.Name = currentAttr.FileAttr
currentAttr.Hidden = false
currentAttr.FilePath = true
value, err = c.promptFieldValue(p, currentAttr)
if err != nil {
return nil, err
}
}
if value != "" {
attrs[currentAttr.Name] = value
}
}
return attrs, nil
}
func (c *addCredentialCommand) promptFieldValue(p *interact.Pollster, attr jujucloud.NamedCredentialAttr) (string, error) {
name := attr.Name
if len(attr.Options) > 0 {
options := make([]string, len(attr.Options))
for i, opt := range attr.Options {
options[i] = fmt.Sprintf("%v", opt)
}
return p.Select(interact.List{
Singular: name,
Plural: name,
Options: options,
Default: options[0],
})
}
// We assume that Hidden, ExpandFilePath and FilePath are mutually
// exclusive here.
switch {
case attr.Hidden:
return p.EnterPassword(name)
case attr.ExpandFilePath:
return enterFile(name, attr.Description, p, true, attr.Optional)
case attr.FilePath:
return enterFile(name, attr.Description, p, false, attr.Optional)
case attr.Optional:
return p.EnterOptional(name)
default:
return p.Enter(name)
}
}
func (c *addCredentialCommand) credentialsAPI() (CredentialAPI, error) {
root, err := c.NewAPIRoot(c.Store, c.ControllerName, "")
if err != nil {
return nil, errors.Trace(err)
}
return apicloud.NewClient(root), nil
}
func (c *addCredentialCommand) maybeRemoteCloud(ctxt *cmd.Context) error {
client, err := c.credentialAPIFunc()
if err != nil {
return err
}
defer client.Close()
// Get user clouds from the controller
remoteUserClouds, err := client.Clouds()
if err != nil {
return err
}
if remoteCloud, ok := remoteUserClouds[names.NewCloudTag(c.CloudName)]; ok {
ctxt.Infof("Using cloud %q from the controller to verify credentials.", c.CloudName)
c.cloud = &remoteCloud
c.remoteCloudFound = true
}
return nil
}
func (c *addCredentialCommand) addRemoteCredentials(ctxt *cmd.Context, all map[string]jujucloud.Credential, localError error) error {
if len(all) == 0 {
fmt.Fprintf(ctxt.Stdout, "No credentials for cloud %q uploaded to controller %q.\n", c.CloudName, c.ControllerName)
return localError
}
if !c.remoteCloudFound {
fmt.Fprintf(ctxt.Stdout, "No cloud %q found on the controller %q: credentials are not uploaded.\n"+
"Use 'juju clouds -c %v' to see what clouds are available on the controller.\n"+
"User 'juju add-cloud %v -c %v' to add your cloud to the controller.\n",
c.CloudName, c.ControllerName, c.ControllerName, c.CloudName, c.ControllerName)
return localError
}
accountDetails, err := c.Store.AccountDetails(c.ControllerName)
if err != nil {
return err
}
verified, erred := verifyCredentialsForUpload(ctxt, accountDetails, c.cloud, c.Region, all)
if len(verified) == 0 {
return erred
}
client, err := c.credentialAPIFunc()
if err != nil {
return err
}
defer client.Close()
results, err := client.UpdateCloudsCredentials(verified)
if err != nil {
logger.Errorf("%v", err)
ctxt.Warningf("Could not upload credentials to controller %q", c.ControllerName)
}
return processUpdateCredentialResult(ctxt, accountDetails, "added", results, c.ControllerName, localError)
}
func enterFile(name, descr string, p *interact.Pollster, expanded, optional bool) (string, error) {
inputSuffix := ""
if optional {
inputSuffix += " (optional)"
}
input, err := p.EnterVerify(fmt.Sprintf("%s%s", descr, inputSuffix), func(s string) (ok bool, msg string, err error) {
if optional && s == "" {
return true, "", nil
}
_, err = jujucloud.ValidateFileAttrValue(s)
if err != nil {
return false, err.Error(), nil
}
return true, "", nil
})
if err != nil {
return "", errors.Trace(err)
}
// If it's optional and the input is empty, then return back out.
if optional && input == "" {
return "", nil
}
// We have to run this twice, since it has glommed together
// validation and normalization, and Pollster doesn't deal with the
// verification function modifying the value.
abs, err := jujucloud.ValidateFileAttrValue(input)
if err != nil {
return "", errors.Trace(err)
}
// If we don't need to expand the file path, exit out early.
if !expanded {
return abs, err
}
// Expand the file path to consume the contents
contents, err := ioutil.ReadFile(abs)
return string(contents), errors.Trace(err)
}
func shouldFinalizeCredential(provider environs.EnvironProvider, cred jujucloud.Credential) bool {
if finalizer, ok := provider.(environs.RequestFinalizeCredential); ok {
return finalizer.ShouldFinalizeCredential(cred)
}
return false
}
func validCloudRegion(aCloud *jujucloud.Cloud, region string) error {
for _, r := range aCloud.Regions {
if r.Name == region {
return nil
}
}
return errors.NotValidf("provided region %q for cloud %q", region, aCloud.Name)
}