github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/juju/cloud/defaultregion.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package cloud 5 6 import ( 7 "fmt" 8 "strings" 9 10 "github.com/juju/cmd" 11 "github.com/juju/errors" 12 13 jujucloud "github.com/juju/juju/cloud" 14 "github.com/juju/juju/cmd/juju/common" 15 "github.com/juju/juju/jujuclient" 16 ) 17 18 type setDefaultRegionCommand struct { 19 cmd.CommandBase 20 21 store jujuclient.CredentialStore 22 cloud string 23 region string 24 } 25 26 var usageSetDefaultRegionSummary = ` 27 Sets the default region for a cloud.`[1:] 28 29 var usageSetDefaultRegionDetails = ` 30 The default region is specified directly as an argument. 31 32 Examples: 33 juju set-default-region azure-china chinaeast 34 35 See also: 36 add-credential`[1:] 37 38 // NewSetDefaultRegionCommand returns a command to set the default region for a cloud. 39 func NewSetDefaultRegionCommand() cmd.Command { 40 return &setDefaultRegionCommand{ 41 store: jujuclient.NewFileCredentialStore(), 42 } 43 } 44 45 func (c *setDefaultRegionCommand) Info() *cmd.Info { 46 return &cmd.Info{ 47 Name: "set-default-region", 48 Args: "<cloud name> <region>", 49 Purpose: usageSetDefaultRegionSummary, 50 Doc: usageSetDefaultRegionDetails, 51 } 52 } 53 54 func (c *setDefaultRegionCommand) Init(args []string) (err error) { 55 if len(args) < 2 { 56 return errors.New("Usage: juju set-default-region <cloud-name> <region>") 57 } 58 c.cloud = args[0] 59 c.region = args[1] 60 return cmd.CheckEmpty(args[2:]) 61 } 62 63 func getRegion(region string, regions []jujucloud.Region) string { 64 for _, r := range regions { 65 if strings.EqualFold(r.Name, region) { 66 return r.Name 67 } 68 } 69 return "" 70 } 71 72 func (c *setDefaultRegionCommand) Run(ctxt *cmd.Context) error { 73 cloudDetails, err := common.CloudOrProvider(c.cloud, jujucloud.CloudByName) 74 if err != nil { 75 return err 76 } 77 if len(cloudDetails.Regions) == 0 { 78 return errors.Errorf("cloud %s has no regions", c.cloud) 79 } 80 if region := getRegion(c.region, cloudDetails.Regions); region == "" { 81 var regionNames []string 82 for _, r := range cloudDetails.Regions { 83 regionNames = append(regionNames, r.Name) 84 } 85 return errors.NewNotValid( 86 nil, 87 fmt.Sprintf("region %q for cloud %s not valid, valid regions are %s", 88 c.region, c.cloud, strings.Join(regionNames, ", "))) 89 } else { 90 c.region = region 91 } 92 var cred *jujucloud.CloudCredential 93 cred, err = c.store.CredentialForCloud(c.cloud) 94 if errors.IsNotFound(err) { 95 cred = &jujucloud.CloudCredential{} 96 } else if err != nil { 97 return err 98 } 99 cred.DefaultRegion = c.region 100 if err := c.store.UpdateCredential(c.cloud, *cred); err != nil { 101 return err 102 } 103 ctxt.Infof("Default region in %s set to %q.", c.cloud, c.region) 104 return nil 105 }