-
Notifications
You must be signed in to change notification settings - Fork 197
/
root.go
207 lines (177 loc) · 6.84 KB
/
root.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package cmd
import (
"encoding/json"
"io"
"os"
"path/filepath"
"github.com/Azure/agentbaker/pkg/agent/datamodel"
"github.com/Azure/agentbaker/pkg/aks-engine/api"
"github.com/Azure/agentbaker/pkg/aks-engine/helpers"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/google/uuid"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
ini "gopkg.in/ini.v1"
)
const (
rootName = "Agent Baker"
rootShortDescription = "AKS Agent Baker prepare agent node bootstrapping data and command"
rootLongDescription = "AKS Agent Baker prepare agent node bootstrapping data and command"
)
var (
debug bool
dumpDefaultModel bool
)
// NewRootCmd returns the root command for AKS Agent Baker.
func NewRootCmd() *cobra.Command {
rootCmd := &cobra.Command{
Use: rootName,
Short: rootShortDescription,
Long: rootLongDescription,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if debug {
log.SetLevel(log.DebugLevel)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
if dumpDefaultModel {
return writeDefaultModel(cmd.OutOrStdout())
}
return cmd.Usage()
},
}
p := rootCmd.PersistentFlags()
p.BoolVar(&debug, "debug", false, "enable verbose debug logs")
f := rootCmd.Flags()
f.BoolVar(&dumpDefaultModel, "show-default-model", false, "Dump the default API model to stdout")
rootCmd.AddCommand(newGenerateCmd())
return rootCmd
}
func writeDefaultModel(out io.Writer) error {
meta, p := api.LoadDefaultContainerServiceProperties()
type withMeta struct {
APIVersion string `json:"apiVersion"`
Properties *datamodel.Properties `json:"properties"`
}
b, err := json.MarshalIndent(withMeta{APIVersion: meta.APIVersion, Properties: p}, "", "\t")
if err != nil {
return errors.Wrap(err, "error encoding model to json")
}
b = append(b, '\n')
if _, err := out.Write(b); err != nil {
return errors.Wrap(err, "error writing output")
}
return nil
}
type authProvider interface {
getAuthArgs() *authArgs
}
type authArgs struct {
RawAzureEnvironment string
rawSubscriptionID string
SubscriptionID uuid.UUID
AuthMethod string
rawClientID string
ClientID uuid.UUID
ClientSecret string
CertificatePath string
PrivateKeyPath string
IdentitySystem string
language string
}
func addAuthFlags(authArgs *authArgs, f *flag.FlagSet) {
f.StringVar(&authArgs.RawAzureEnvironment, "azure-env", "AzurePublicCloud", "the target Azure cloud")
f.StringVarP(&authArgs.rawSubscriptionID, "subscription-id", "s", "", "azure subscription id (required)")
f.StringVar(&authArgs.AuthMethod, "auth-method", "client_secret", "auth method (default:`client_secret`, `cli`, `client_certificate`, `device`)")
f.StringVar(&authArgs.rawClientID, "client-id", "", "client id (used with --auth-method=[client_secret|client_certificate])")
f.StringVar(&authArgs.ClientSecret, "client-secret", "", "client secret (used with --auth-method=client_secret)")
f.StringVar(&authArgs.CertificatePath, "certificate-path", "", "path to client certificate (used with --auth-method=client_certificate)")
f.StringVar(&authArgs.PrivateKeyPath, "private-key-path", "", "path to private key (used with --auth-method=client_certificate)")
f.StringVar(&authArgs.IdentitySystem, "identity-system", "azure_ad", "identity system (default:`azure_ad`, `adfs`)")
f.StringVar(&authArgs.language, "language", "en-us", "language to return error messages in")
}
//this allows the authArgs to be stubbed behind the authProvider interface, and be its own provider when not in tests.
func (authArgs *authArgs) getAuthArgs() *authArgs {
return authArgs
}
func (authArgs *authArgs) validateAuthArgs() error {
authArgs.ClientID, _ = uuid.Parse(authArgs.rawClientID)
authArgs.SubscriptionID, _ = uuid.Parse(authArgs.rawSubscriptionID)
if authArgs.AuthMethod == "client_secret" {
if authArgs.ClientID.String() == "00000000-0000-0000-0000-000000000000" || authArgs.ClientSecret == "" {
return errors.New(`--client-id and --client-secret must be specified when --auth-method="client_secret"`)
}
// try parse the UUID
} else if authArgs.AuthMethod == "client_certificate" {
if authArgs.ClientID.String() == "00000000-0000-0000-0000-000000000000" || authArgs.CertificatePath == "" || authArgs.PrivateKeyPath == "" {
return errors.New(`--client-id and --certificate-path, and --private-key-path must be specified when --auth-method="client_certificate"`)
}
}
if authArgs.SubscriptionID.String() == "00000000-0000-0000-0000-000000000000" {
subID, err := getSubFromAzDir(filepath.Join(helpers.GetHomeDir(), ".azure"))
if err != nil || subID.String() == "00000000-0000-0000-0000-000000000000" {
return errors.New("--subscription-id is required (and must be a valid UUID)")
}
log.Infoln("No subscription provided, using selected subscription from azure CLI:", subID.String())
authArgs.SubscriptionID = subID
}
_, err := azure.EnvironmentFromName(authArgs.RawAzureEnvironment)
if err != nil {
return errors.New("failed to parse --azure-env as a valid target Azure cloud environment")
}
return nil
}
func getSubFromAzDir(root string) (uuid.UUID, error) {
subConfig, err := ini.Load(filepath.Join(root, "clouds.config"))
if err != nil {
return uuid.UUID{}, errors.Wrap(err, "error decoding cloud subscription config")
}
cloudConfig, err := ini.Load(filepath.Join(root, "config"))
if err != nil {
return uuid.UUID{}, errors.Wrap(err, "error decoding cloud config")
}
cloud := getSelectedCloudFromAzConfig(cloudConfig)
return getCloudSubFromAzConfig(cloud, subConfig)
}
func getSelectedCloudFromAzConfig(f *ini.File) string {
selectedCloud := "AzureCloud"
if cloud, err := f.GetSection("cloud"); err == nil {
if name, err := cloud.GetKey("name"); err == nil {
if s := name.String(); s != "" {
selectedCloud = s
}
}
}
return selectedCloud
}
func getCloudSubFromAzConfig(cloud string, f *ini.File) (uuid.UUID, error) {
cfg, err := f.GetSection(cloud)
if err != nil {
return uuid.UUID{}, errors.New("could not find user defined subscription id")
}
sub, err := cfg.GetKey("subscription")
if err != nil {
return uuid.UUID{}, errors.Wrap(err, "error reading subscription id from cloud config")
}
return uuid.Parse(sub.String())
}
func getCompletionCmd(root *cobra.Command) *cobra.Command {
var completionCmd = &cobra.Command{
Use: "completion",
Short: "Generates bash completion scripts",
Long: `To load completion run
source <(aks-engine completion)
To configure your bash shell to load completions for each session, add this to your bashrc
# ~/.bashrc or ~/.profile
source <(aks-engine completion)
`,
RunE: func(cmd *cobra.Command, args []string) error {
return root.GenBashCompletion(os.Stdout)
},
}
return completionCmd
}