forked from Azure/aztfexport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflag.go
422 lines (393 loc) · 12.2 KB
/
flag.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
package main
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"strings"
"github.com/Azure/aztfexport/internal/cfgfile"
"github.com/Azure/aztfexport/internal/log"
"github.com/Azure/aztfexport/pkg/config"
"github.com/Azure/aztfexport/pkg/telemetry"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/gofrs/uuid"
"github.com/urfave/cli/v2"
)
var flagset FlagSet
type FlagSet struct {
// common flags
flagEnv string
flagSubscriptionId string
flagOutputDir string
flagOverwrite bool
flagAppend bool
flagDevProvider bool
flagProviderVersion string
flagProviderName string
flagBackendType string
flagBackendConfig cli.StringSlice
flagFullConfig bool
flagParallelism int
flagContinue bool
flagNonInteractive bool
flagPlainUI bool
flagGenerateMappingFile bool
flagHCLOnly bool
flagModulePath string
flagGenerateImportBlock bool
flagLogPath string
flagLogLevel string
// common flags (auth)
flagUseEnvironmentCred bool
flagUseManagedIdentityCred bool
flagUseAzureCLICred bool
flagUseOIDCCred bool
flagOIDCRequestToken string
flagOIDCRequestURL string
flagOIDCTokenFilePath string
flagOIDCToken string
// common flags (hidden)
hflagMockClient bool
hflagProfile string
hflagTFClientPluginPath string
// Subcommand specific flags
//
// res:
// flagResName
// flagResType
//
// rg:
// flagPattern
// flagIncludeRoleAssignment
//
// query:
// flagPattern
// flagRecursive
// flagIncludeRoleAssignment
// flagIncludeResourceGroup
flagPattern string
flagRecursive bool
flagResName string
flagResType string
flagIncludeRoleAssignment bool
flagIncludeResourceGroup bool
}
const (
ModeResource = "resource"
ModeResourceGroup = "resource-group"
ModeQuery = "query"
ModeMappingFile = "mapping-file"
)
// DescribeCLI construct a description of the CLI based on the flag set and the specified mode.
// The main reason is to record the usage of some "interesting" options in the telemetry.
// Note that only insensitive values are recorded (i.e. subscription id, resource id, etc are not recorded)
func (flag FlagSet) DescribeCLI(mode string) string {
args := []string{mode}
// The following flags are skipped eiter not interesting, or might contain sensitive info:
// - flagSubscriptionId
// - flagOutputDir
// - flagDevProvider
// - flagBackendConfig
// - all hflags
if flag.flagEnv != "" {
args = append(args, "--env="+flag.flagEnv)
}
if flag.flagOverwrite {
args = append(args, "--overwrite=true")
}
if flag.flagAppend {
args = append(args, "--append=true")
}
if flag.flagProviderVersion != "" {
args = append(args, fmt.Sprintf(`-provider-version=%s`, flag.flagProviderVersion))
}
if flag.flagProviderName != "" {
args = append(args, fmt.Sprintf(`-provider-name=%s`, flag.flagProviderName))
}
if flag.flagBackendType != "" {
args = append(args, "--backend-type="+flag.flagBackendType)
}
if flag.flagFullConfig {
args = append(args, "--full-properties=true")
}
if flag.flagParallelism != 0 {
args = append(args, fmt.Sprintf("--parallelism=%d", flag.flagParallelism))
}
if flag.flagNonInteractive {
args = append(args, "--non-interactive=true")
}
if flag.flagPlainUI {
args = append(args, "--plain-ui=true")
}
if flag.flagContinue {
args = append(args, "--continue=true")
}
if flag.flagGenerateMappingFile {
args = append(args, "--generate-mapping-file=true")
}
if flag.flagHCLOnly {
args = append(args, "--hcl-only=true")
}
if flag.flagModulePath != "" {
args = append(args, "--module-path="+flag.flagModulePath)
}
if !flag.flagGenerateImportBlock {
args = append(args, "--generate-import-block=true")
}
if flag.flagUseEnvironmentCred {
args = append(args, "--use-environment-cred=true")
}
if flag.flagUseManagedIdentityCred {
args = append(args, "--use-managed-identity-cred=true")
}
if flag.flagUseAzureCLICred {
args = append(args, "--use-azure-cli-cred=true")
}
if flag.flagUseOIDCCred {
args = append(args, "--use-oidc-cred=true")
}
if flag.flagOIDCRequestToken != "" {
args = append(args, "--oidc-request-token=*")
}
if flag.flagOIDCRequestURL != "" {
args = append(args, "--oidc-request-url="+flag.flagOIDCRequestURL)
}
if flag.flagOIDCTokenFilePath != "" {
args = append(args, "--oidc-token-file-path="+flag.flagOIDCTokenFilePath)
}
if flag.flagOIDCToken != "" {
args = append(args, "--oidc-token=*")
}
if flag.hflagTFClientPluginPath != "" {
args = append(args, "--tfclient-plugin-path="+flag.hflagTFClientPluginPath)
}
switch mode {
case ModeResource:
if flag.flagResName != "" {
args = append(args, "--name="+flag.flagResName)
}
if flag.flagResType != "" {
args = append(args, "--type="+flag.flagResType)
}
case ModeResourceGroup:
if flag.flagPattern != "" {
args = append(args, "--name-pattern="+flag.flagPattern)
}
if flag.flagIncludeRoleAssignment {
args = append(args, "--include-role-assignment=true")
}
case ModeQuery:
if flag.flagPattern != "" {
args = append(args, "--name-pattern="+flag.flagPattern)
}
if flag.flagRecursive {
args = append(args, "--recursive=true")
}
if flag.flagIncludeRoleAssignment {
args = append(args, "--include-role-assignment=true")
}
if flag.flagIncludeResourceGroup {
args = append(args, "--include-resource-group=true")
}
}
return "aztfexport " + strings.Join(args, " ")
}
func initTelemetryClient(subscriptionId string) telemetry.Client {
cfg, err := cfgfile.GetConfig()
if err != nil {
return telemetry.NewNullClient()
}
enabled, installId := cfg.TelemetryEnabled, cfg.InstallationId
if !enabled {
return telemetry.NewNullClient()
}
if installId == "" {
uuid, err := uuid.NewV4()
if err == nil {
installId = uuid.String()
} else {
installId = "undefined"
}
}
sessionId := "undefined"
if uuid, err := uuid.NewV4(); err == nil {
sessionId = uuid.String()
}
return telemetry.NewAppInsight(subscriptionId, installId, sessionId)
}
// buildAzureSDKCredAndClientOpt builds the Azure SDK credential and client option from multiple sources (i.e. environment variables, MSI, Azure CLI).
func buildAzureSDKCredAndClientOpt(fset FlagSet) (azcore.TokenCredential, *arm.ClientOptions, error) {
var cloudCfg cloud.Configuration
switch env := fset.flagEnv; strings.ToLower(env) {
case "public":
cloudCfg = cloud.AzurePublic
case "usgovernment":
cloudCfg = cloud.AzureGovernment
case "china":
cloudCfg = cloud.AzureChina
default:
return nil, nil, fmt.Errorf("unknown environment specified: %q", env)
}
// Maps the auth related environment variables used in the provider to what azidentity honors
if v, ok := os.LookupEnv("ARM_TENANT_ID"); ok {
// #nosec G104
os.Setenv("AZURE_TENANT_ID", v)
}
if v, ok := os.LookupEnv("ARM_CLIENT_ID"); ok {
// #nosec G104
os.Setenv("AZURE_CLIENT_ID", v)
}
if v, ok := os.LookupEnv("ARM_CLIENT_SECRET"); ok {
// #nosec G104
os.Setenv("AZURE_CLIENT_SECRET", v)
}
if v, ok := os.LookupEnv("ARM_CLIENT_CERTIFICATE_PATH"); ok {
// #nosec G104
os.Setenv("AZURE_CLIENT_CERTIFICATE_PATH", v)
}
clientOpt := &arm.ClientOptions{
ClientOptions: policy.ClientOptions{
Cloud: cloudCfg,
Telemetry: policy.TelemetryOptions{
ApplicationID: fmt.Sprintf("aztfexport(%s)", fset.flagProviderName),
Disabled: false,
},
Logging: policy.LogOptions{
IncludeBody: true,
},
},
}
tenantId := os.Getenv("ARM_TENANT_ID")
var (
cred azcore.TokenCredential
err error
)
switch {
case fset.flagUseEnvironmentCred:
cred, err = azidentity.NewEnvironmentCredential(&azidentity.EnvironmentCredentialOptions{
ClientOptions: clientOpt.ClientOptions,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to new Environment credential: %v", err)
}
return cred, clientOpt, nil
case fset.flagUseManagedIdentityCred:
cred, err = azidentity.NewManagedIdentityCredential(&azidentity.ManagedIdentityCredentialOptions{
ClientOptions: clientOpt.ClientOptions,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to new Managed Identity credential: %v", err)
}
return cred, clientOpt, nil
case fset.flagUseAzureCLICred:
cred, err = azidentity.NewAzureCLICredential(&azidentity.AzureCLICredentialOptions{
TenantID: tenantId,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to new Azure CLI credential: %v", err)
}
return cred, clientOpt, nil
case fset.flagUseOIDCCred:
cred, err = NewOidcCredential(&OidcCredentialOptions{
ClientOptions: clientOpt.ClientOptions,
TenantID: tenantId,
ClientID: os.Getenv("ARM_CLIENT_ID"),
RequestToken: fset.flagOIDCRequestToken,
RequestUrl: fset.flagOIDCRequestURL,
Token: fset.flagOIDCToken,
TokenFilePath: fset.flagOIDCTokenFilePath,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to new OIDC credential: %v", err)
}
return cred, clientOpt, nil
default:
opt := &azidentity.DefaultAzureCredentialOptions{
ClientOptions: clientOpt.ClientOptions,
TenantID: tenantId,
}
cred, err := azidentity.NewDefaultAzureCredential(opt)
if err != nil {
return nil, nil, fmt.Errorf("failed to new Default credential: %v", err)
}
return cred, clientOpt, nil
}
}
// BuildCommonConfig builds the CommonConfig from the FlagSet, except the TFClient, which is built afterwards as it requires a logger.
func (f FlagSet) BuildCommonConfig() (config.CommonConfig, error) {
cred, clientOpt, err := buildAzureSDKCredAndClientOpt(f)
if err != nil {
return config.CommonConfig{}, err
}
cfg := config.CommonConfig{
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
SubscriptionId: f.flagSubscriptionId,
AzureSDKCredential: cred,
AzureSDKClientOption: *clientOpt,
OutputDir: f.flagOutputDir,
ProviderVersion: f.flagProviderVersion,
ProviderName: f.flagProviderName,
DevProvider: f.flagDevProvider,
ContinueOnError: f.flagContinue,
BackendType: f.flagBackendType,
BackendConfig: f.flagBackendConfig.Value(),
FullConfig: f.flagFullConfig,
Parallelism: f.flagParallelism,
HCLOnly: f.flagHCLOnly,
ModulePath: f.flagModulePath,
GenerateImportBlock: f.flagGenerateImportBlock,
TelemetryClient: initTelemetryClient(f.flagSubscriptionId),
}
if f.flagAppend {
cfg.OutputFileNames = config.OutputFileNames{
TerraformFileName: "terraform.aztfexport.tf",
ProviderFileName: "provider.aztfexport.tf",
MainFileName: "main.aztfexport.tf",
ImportBlockFileName: "import.aztfexport.tf",
}
}
// Logger is only enabled when the log path is specified.
// This is because either interactive/non-interactive mode controls the terminal rendering,
// logging to stdout/stderr will impact the rendering.
if path := f.flagLogPath; path != "" {
level, err := logLevel(f.flagLogLevel)
if err != nil {
return config.CommonConfig{}, err
}
// #nosec G304
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return config.CommonConfig{}, fmt.Errorf("creating log file %s: %v", path, err)
}
logger := slog.New(slog.NewTextHandler(f, &slog.HandlerOptions{Level: level}))
// Enable log for azure sdk
os.Setenv("AZURE_SDK_GO_LOGGING", "all") // #nosec G104
azlog.SetListener(func(cls azlog.Event, msg string) {
logger.Log(context.Background(), log.LevelTrace, msg, "event", cls)
})
cfg.Logger = logger
}
return cfg, nil
}
func logLevel(level string) (slog.Level, error) {
switch strings.ToUpper(level) {
case "ERROR":
return slog.LevelError, nil
case "WARN":
return slog.LevelWarn, nil
case "INFO":
return slog.LevelInfo, nil
case "DEBUG":
return slog.LevelDebug, nil
case "TRACE":
return log.LevelTrace, nil
default:
return slog.Level(0), fmt.Errorf("unknown log level: %s", level)
}
}