/
jenv.go
188 lines (165 loc) · 5.69 KB
/
jenv.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package environment
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/names"
"gopkg.in/yaml.v1"
"github.com/juju/juju/cmd/envcmd"
"github.com/juju/juju/environs/configstore"
"github.com/juju/juju/juju/osenv"
)
// JenvCommand imports the given Juju generated jenv file into the local
// JUJU_HOME environments directory.
type JenvCommand struct {
cmd.CommandBase
jenvFile cmd.FileVar
envName string
}
const jenvHelpDoc = `
Copy the provided Juju generated jenv file to the proper location inside your
local JUJU_HOME. Also switch to using the resulting environment as the default
one. This way it is possible to import and use jenv files generated by other
Juju commands such as "juju user add".
Example:
juju environment jenv my-env.jenv (my-env.jenv is the path to the jenv file)
juju environment jenv my-env.jenv ec2 (copy and rename the environment)
`
func (c *JenvCommand) Info() *cmd.Info {
return &cmd.Info{
Name: "jenv",
Args: "<path/to/file.jenv> [<environment name>]",
Purpose: "import previously generated Juju environment files",
Doc: strings.TrimSpace(jenvHelpDoc),
}
}
func (c *JenvCommand) Init(args []string) error {
if len(args) == 0 {
return errors.New("no jenv file provided")
}
// Store the path to the jenv file.
if err := c.jenvFile.Set(args[0]); err != nil {
return errors.Annotate(err, "invalid jenv path")
}
args = args[1:]
if len(args) > 0 {
// Store and validate the provided environment name.
c.envName, args = args[0], args[1:]
if !names.IsValidUser(c.envName) {
return errors.Errorf("invalid environment name %q", c.envName)
}
} else {
// Retrieve the environment name from the jenv file name.
base := filepath.Base(c.jenvFile.Path)
c.envName = base[:len(base)-len(filepath.Ext(base))]
}
// No other arguments are expected.
return cmd.CheckEmpty(args)
}
func (c *JenvCommand) Run(ctx *cmd.Context) error {
// Read data from the provided jenv file.
data, err := c.jenvFile.Read(ctx)
if err != nil {
if os.IsNotExist(errors.Cause(err)) {
return errors.NotFoundf("jenv file %q", c.jenvFile.Path)
}
return errors.Annotatef(err, "cannot read the provided jenv file %q", c.jenvFile.Path)
}
// Open the config store.
store, err := configstore.Default()
if err != nil {
return errors.Annotate(err, "cannot get config store")
}
// Create and update the new environment info object.
info := store.CreateInfo(c.envName)
if err := updateEnvironmentInfo(info, data); err != nil {
return errors.Annotatef(err, "invalid jenv file %q", c.jenvFile.Path)
}
// Write the environment info to JUJU_HOME.
if err := info.Write(); err != nil {
if errors.Cause(err) == configstore.ErrEnvironInfoAlreadyExists {
descriptiveErr := errors.Errorf("an environment named %q already exists: "+
"you can provide a second parameter to rename the environment",
c.envName)
return errors.Wrap(err, descriptiveErr)
}
return errors.Annotate(err, "cannot write the jenv file")
}
// Switch to the new environment.
oldEnvName, err := switchEnvironment(c.envName)
if err != nil {
return errors.Annotatef(err, "cannot switch to the new environment %q", c.envName)
}
if oldEnvName == "" {
fmt.Fprintf(ctx.Stdout, "-> %s\n", c.envName)
} else {
fmt.Fprintf(ctx.Stdout, "%s -> %s\n", oldEnvName, c.envName)
}
return nil
}
// updateEnvironmentInfo updates the given environment info with the values
// stored in the provided YAML encoded data.
func updateEnvironmentInfo(info configstore.EnvironInfo, data []byte) error {
var values configstore.EnvironInfoData
if err := yaml.Unmarshal(data, &values); err != nil {
return errors.Annotate(err, "cannot unmarshal jenv data")
}
// Ensure the required values are present.
if missing := getMissingEnvironmentInfoFields(values); len(missing) != 0 {
return errors.Errorf("missing required fields in jenv data: %s", strings.Join(missing, ", "))
}
// Update the environment info.
info.SetAPICredentials(configstore.APICredentials{
User: values.User,
Password: values.Password,
})
info.SetAPIEndpoint(configstore.APIEndpoint{
Addresses: values.StateServers,
Hostnames: values.ServerHostnames,
CACert: values.CACert,
EnvironUUID: values.EnvironUUID,
})
info.SetBootstrapConfig(values.Config)
return nil
}
// getMissingEnvironmentInfoFields returns a list of field names missing in the
// given environment info values. The only fields taken into consideration here
// are the ones explicitly set by the "juju user add" command.
func getMissingEnvironmentInfoFields(values configstore.EnvironInfoData) (missing []string) {
if values.User == "" {
missing = append(missing, "User")
}
if values.Password == "" {
missing = append(missing, "Password")
}
if values.EnvironUUID == "" {
missing = append(missing, "EnvironUUID")
}
if len(values.StateServers) == 0 {
missing = append(missing, "StateServers")
}
if values.CACert == "" {
missing = append(missing, "CACert")
}
return missing
}
// switchEnvironment changes the default environment to the given name and
// return, if set, the current default environment name.
func switchEnvironment(envName string) (string, error) {
if defaultEnv := os.Getenv(osenv.JujuEnvEnvKey); defaultEnv != "" {
return "", errors.Errorf("cannot switch when %s is overriding the environment (set to %q)", osenv.JujuEnvEnvKey, defaultEnv)
}
currentEnv, err := envcmd.GetDefaultEnvironment()
if err != nil {
return "", errors.Annotate(err, "cannot get the default environment")
}
if err := envcmd.WriteCurrentEnvironment(envName); err != nil {
return "", errors.Trace(err)
}
return currentEnv, nil
}