/
generate_gke.go
505 lines (440 loc) · 16.3 KB
/
generate_gke.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
package cmd
import (
"time"
"github.com/lacework/go-sdk/lwgenerate/gcp"
"github.com/AlecAivazis/survey/v2"
"github.com/imdario/mergo"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
type GkeGenerateCommandExtraState struct {
AskAdvanced bool
Output string
ConfigureNewBucketSettings bool
UseExistingServiceAccount bool
UseExistingSink bool
TerraformApply bool
}
func (g *GkeGenerateCommandExtraState) isEmpty() bool {
return g.Output == "" &&
!g.AskAdvanced &&
!g.UseExistingServiceAccount &&
!g.UseExistingSink &&
!g.TerraformApply
}
func (g *GkeGenerateCommandExtraState) writeCache() {
if !g.isEmpty() {
cli.WriteAssetToCache(CachedGkeAssetExtraState, time.Now().Add(time.Hour*1), g)
}
}
var (
QuestionGkeOrganizationIntegration = "Organization integration?"
QuestionGkeOrganizationID = "Specify the GCP organization ID:"
QuestionGkeProjectID = "Specify the project ID to be used to provision Lacework resources:"
QuestionGkeServiceAccountCredsPath = "Specify service account credentials JSON path: (optional)"
QuestionGkeConfigureAdvanced = "Configure advanced integration options?"
GkeAdvancedOpt = "Configure additional options"
QuestionGkeUseExistingSink = "Use an existing sink?"
QuestionGkeExistingSinkName = "Specify the existing sink name"
GkeAdvancedOptIntegrationName = "Customize integration name(s)"
QuestionGkeIntegrationName = "Specify a custom integration name: (optional)"
GkeAdvancedOptExistingServiceAccount = "Configure & use existing service account"
QuestionGkeExistingServiceAccountName = "Specify an existing service account name:"
QuestionGkeExistingServiceAccountPrivateKey = "Specify an existing service account private key" +
" (base64 encoded):" // guardrails-disable-line
GkeAdvancedOptLocation = "Customize output location"
QuestionGkeCustomizeOutputLocation = "Provide the location for the output to be written:"
QuestionGkeAnotherAdvancedOpt = "Configure another advanced integration option"
GkeAdvancedOptDone = "Done"
GenerateGkeCommandState = &gcp.GenerateGkeTfConfigurationArgs{}
GenerateGkeExistingServiceAccount = &gcp.ServiceAccount{}
GenerateGkeCommandExtraState = &GkeGenerateCommandExtraState{}
CachedGkeAssetIacParams = "iac-gke-generate-params"
CachedGkeAssetExtraState = "iac-gke-extra-state"
generateGkeTfCommand = &cobra.Command{
Use: "gke",
Short: "Generate and/or execute Terraform code for GKE integration",
Long: `Use this command to generate Terraform code for deploying Lacework into a GKE environment.
By default, this command interactively prompts for the required information to setup the new cloud account.
In interactive mode, this command will:
* Prompt for the required information to setup the integration
* Generate new Terraform code using the inputs
* Optionally, run the generated Terraform code:
* If Terraform is already installed, the version is verified as compatible for use
* If Terraform is not installed, or the version installed is not compatible, a new
version will be installed into a temporary location
* Once Terraform is detected or installed, Terraform plan will be executed
* The command will prompt with the outcome of the plan and allow to view more details
or continue with Terraform apply
* If confirmed, Terraform apply will be run, completing the setup of the cloud account
This command can also be run in noninteractive mode.
See help output for more details on the parameter value(s) required for Terraform code generation.
`,
RunE: func(cmd *cobra.Command, args []string) error {
cli.StartProgress("Generating Terraform Code...")
if cli.Profile != "default" {
GenerateGkeCommandState.LaceworkProfile = cli.Profile
}
mods := []gcp.Modifier{
gcp.WithGkeExistingServiceAccount(GenerateGkeCommandState.ExistingServiceAccount),
gcp.WithGkeExistingSinkName(GenerateGkeCommandState.ExistingSinkName),
gcp.WithGkeIntegrationName(GenerateGkeCommandState.IntegrationName),
gcp.WithGkeLabels(GenerateGkeCommandState.Labels),
gcp.WithGkeLaceworkProfile(GenerateGkeCommandState.LaceworkProfile),
gcp.WithGkeOrganizationId(GenerateGkeCommandState.OrganizationId),
gcp.WithGkeOrganizationIntegration(GenerateGkeCommandState.OrganizationIntegration),
gcp.WithGkePrefix(GenerateGkeCommandState.Prefix),
gcp.WithGkeProjectId(GenerateGkeCommandState.ProjectId),
gcp.WithGkePubSubSubscriptionLabels(GenerateGkeCommandState.PubSubSubscriptionLabels),
gcp.WithGkePubSubTopicLabels(GenerateGkeCommandState.PubSubTopicLabels),
gcp.WithGkeServiceAccountCredentials(GenerateGkeCommandState.ServiceAccountCredentials),
gcp.WithGkeWaitTime(GenerateGkeCommandState.WaitTime),
}
hcl, err := gcp.NewGkeTerraform(mods...).Generate()
cli.StopProgress()
if err != nil {
return errors.Wrap(err, "failed to generate terraform code")
}
dirname, _, err := writeGeneratedCodeToLocation(cmd, hcl, "gke")
if err != nil {
return err
}
err = SurveyQuestionInteractiveOnly(SurveyQuestionWithValidationArgs{
Prompt: &survey.Confirm{Default: GenerateGkeCommandExtraState.TerraformApply, Message: QuestionRunTfPlan},
Response: &GenerateGkeCommandExtraState.TerraformApply,
})
if err != nil {
return errors.Wrap(err, "failed to prompt for terraform execution")
}
locationDir, _ := determineOutputDirPath(dirname, "gke")
if GenerateGkeCommandExtraState.TerraformApply {
err := executionPreRunChecks(dirname, locationDir, "gke")
if err != nil {
return err
}
}
if !GenerateGkeCommandExtraState.TerraformApply {
cli.OutputHuman(provideGuidanceAfterExit(false, false, locationDir, "terraform"))
}
return nil
},
PreRunE: func(cmd *cobra.Command, args []string) error {
var err error
if err = gkeValidation(cmd); err != nil {
return err
}
if cli.InteractiveMode() {
if err = gkeCaching(); err != nil {
return err
}
}
err = promptGkeGenerate(GenerateGkeCommandState, GenerateGkeExistingServiceAccount, GenerateGkeCommandExtraState)
if err != nil {
return errors.Wrap(err, "collecting/confirming parameters")
}
return nil
},
}
)
func gkeValidation(cmd *cobra.Command) error {
dirname, err := cmd.Flags().GetString("output")
if err != nil {
return errors.Wrap(err, "failed to load command flags")
}
if err := validateOutputLocation(dirname); err != nil {
return err
}
gcpSaCredentials, err := cmd.Flags().GetString("service_account_credentials")
if err != nil {
return errors.Wrap(err, "failed to load command flags")
}
if gcpSaCredentials != "" {
if err := gcp.ValidateServiceAccountCredentialsFile(gcpSaCredentials); err != nil {
return err
}
}
projectId, err := cmd.Flags().GetString("project_id")
if err != nil {
return errors.Wrap(err, "failed to load command flags")
}
if projectId == "" && !cli.InteractiveMode() {
return errors.New("project_id must be provided")
}
return nil
}
func gkeCaching() error {
cachedOptions := &gcp.GenerateGkeTfConfigurationArgs{}
iacParamsExpired := cli.ReadCachedAsset(CachedGkeAssetIacParams, &cachedOptions)
if iacParamsExpired {
cli.Log.Debug("loaded previously set values for GCP iac generation")
}
extraState := &GkeGenerateCommandExtraState{}
extraStateParamsExpired := cli.ReadCachedAsset(CachedGkeAssetExtraState, &extraState)
if extraStateParamsExpired {
cli.Log.Debug("loaded previously set values for GCP iac generation (extra state)")
}
answer := false
if !iacParamsExpired || !extraStateParamsExpired {
if err := SurveyQuestionInteractiveOnly(SurveyQuestionWithValidationArgs{
Prompt: &survey.Confirm{Message: QuestionUsePreviousCache, Default: false},
Response: &answer,
}); err != nil {
return errors.Wrap(err, "failed to load saved options")
}
}
if answer {
if err := mergo.Merge(GenerateGkeCommandState, cachedOptions); err != nil {
return errors.Wrap(err, "failed to load saved options")
}
if err := mergo.Merge(GenerateGkeCommandExtraState, extraState); err != nil {
return errors.Wrap(err, "failed to load saved options")
}
}
return nil
}
func initGenerateGkeTfCommandFlags() {
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeExistingServiceAccount.Name,
"existing_service_account_name",
"",
"specify existing service account name")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeExistingServiceAccount.PrivateKey,
"existing_service_account_private_key",
"",
"specify existing service account private key (base64 encoded)")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.ExistingSinkName,
"existing_sink_name",
"",
"specify existing sink name")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.IntegrationName,
"integration_name",
"",
"specify a custom integration name")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.OrganizationId,
"organization_id",
"",
"specify the organization id (only set if organization_integration is set)")
generateGkeTfCommand.PersistentFlags().BoolVar(
&GenerateGkeCommandState.OrganizationIntegration,
"organization_integration",
false,
"enable organization integration")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.Prefix,
"prefix",
"",
"prefix that will be used at the beginning of every generated resource")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.ProjectId,
"project_id",
"",
"specify the project id to be used to provision lacework resources (required)")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.ServiceAccountCredentials,
"service_account_credentials",
"",
"specify service account credentials JSON file path (leave blank to make use of google credential ENV vars)")
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandState.WaitTime,
"wait_time",
"",
"amount of time to wait before the next resource is provisioned")
generateGkeTfCommand.PersistentFlags().BoolVar(
&GenerateGkeCommandExtraState.TerraformApply,
"apply",
false,
"run terraform apply without executing plan or prompting",
)
generateGkeTfCommand.PersistentFlags().StringVar(
&GenerateGkeCommandExtraState.Output,
"output",
"",
"location to write generated content (default is ~/lacework/gcp)",
)
}
func gkeConfigIsEmpty(g *gcp.GenerateGkeTfConfigurationArgs) bool {
return g.ServiceAccountCredentials == "" &&
g.ProjectId == "" &&
g.OrganizationId == "" &&
g.LaceworkProfile == ""
}
func writeGkeGenerationArgsCache(a *gcp.GenerateGkeTfConfigurationArgs) {
if !gkeConfigIsEmpty(a) {
if a.ExistingServiceAccount.IsPartial() {
a.ExistingServiceAccount = nil
}
cli.WriteAssetToCache(CachedGkeAssetIacParams, time.Now().Add(time.Hour*1), a)
}
}
func promptGkeGenerate(
config *gcp.GenerateGkeTfConfigurationArgs,
existingServiceAccount *gcp.ServiceAccount,
extraState *GkeGenerateCommandExtraState,
) error {
if cli.InteractiveMode() {
defer writeGkeGenerationArgsCache(config)
defer extraState.writeCache()
}
if existingServiceAccount.Name != "" ||
existingServiceAccount.PrivateKey != "" {
config.ExistingServiceAccount = existingServiceAccount
}
if err := SurveyMultipleQuestionWithValidation(
[]SurveyQuestionWithValidationArgs{
{
Prompt: &survey.Input{Message: QuestionGkeProjectID, Default: config.ProjectId},
Required: true,
Opts: []survey.AskOpt{survey.WithValidator(validateGcpProjectId)},
Response: &config.ProjectId,
},
{
Prompt: &survey.Confirm{Message: QuestionGkeOrganizationIntegration, Default: config.OrganizationIntegration},
Response: &config.OrganizationIntegration,
},
{
Prompt: &survey.Input{Message: QuestionGkeOrganizationID, Default: config.OrganizationId},
Checks: []*bool{&config.OrganizationIntegration},
Required: true,
Response: &config.OrganizationId,
},
{
Prompt: &survey.Input{Message: QuestionGkeServiceAccountCredsPath, Default: config.ServiceAccountCredentials},
Opts: []survey.AskOpt{survey.WithValidator(gcp.ValidateServiceAccountCredentials)},
Response: &config.ServiceAccountCredentials,
},
}); err != nil {
return err
}
if err := SurveyQuestionInteractiveOnly(SurveyQuestionWithValidationArgs{
Prompt: &survey.Confirm{Message: QuestionGkeConfigureAdvanced, Default: extraState.AskAdvanced},
Response: &extraState.AskAdvanced,
}); err != nil {
return err
}
if extraState.AskAdvanced {
if err := promptGkeAdvancedOptions(config, extraState); err != nil {
return err
}
}
return nil
}
func promptGkeAdvancedOptions(
config *gcp.GenerateGkeTfConfigurationArgs, extraState *GkeGenerateCommandExtraState,
) error {
answer := ""
options := []string{
GkeAdvancedOpt,
GkeAdvancedOptExistingServiceAccount,
GkeAdvancedOptIntegrationName,
GkeAdvancedOptLocation,
GkeAdvancedOptDone,
}
for answer != GkeAdvancedOptDone {
if err := SurveyQuestionInteractiveOnly(SurveyQuestionWithValidationArgs{
Prompt: &survey.Select{
Message: "Which options would you like to configure?",
Options: options,
},
Response: &answer,
}); err != nil {
return err
}
switch answer {
case GkeAdvancedOpt:
if err := promptGkeQuestions(config, extraState); err != nil {
return err
}
case GkeAdvancedOptExistingServiceAccount:
if err := promptGkeExistingServiceAccountQuestions(config); err != nil {
return err
}
case GkeAdvancedOptIntegrationName:
if err := promptGkeIntegrationNameQuestions(config); err != nil {
return err
}
case GkeAdvancedOptLocation:
if err := promptCustomizeGkeOutputLocation(extraState); err != nil {
return err
}
}
innerAskAgain := true
if answer == GkeAdvancedOptDone {
innerAskAgain = false
}
if err := SurveyQuestionInteractiveOnly(SurveyQuestionWithValidationArgs{
Checks: []*bool{&innerAskAgain},
Prompt: &survey.Confirm{Message: QuestionGkeAnotherAdvancedOpt, Default: false},
Response: &innerAskAgain,
}); err != nil {
return err
}
if !innerAskAgain {
answer = GkeAdvancedOptDone
}
}
return nil
}
func promptGkeQuestions(config *gcp.GenerateGkeTfConfigurationArgs, extraState *GkeGenerateCommandExtraState) error {
err := SurveyMultipleQuestionWithValidation([]SurveyQuestionWithValidationArgs{
{
Prompt: &survey.Confirm{Message: QuestionGkeUseExistingSink, Default: extraState.UseExistingSink},
Required: true,
Response: &extraState.UseExistingSink,
},
{
Prompt: &survey.Input{Message: QuestionGkeExistingSinkName, Default: config.ExistingSinkName},
Checks: []*bool{&extraState.UseExistingSink},
Required: true,
Response: &config.ExistingSinkName,
},
})
return err
}
func promptGkeExistingServiceAccountQuestions(config *gcp.GenerateGkeTfConfigurationArgs) error {
if config.ExistingServiceAccount == nil {
config.ExistingServiceAccount = &gcp.ServiceAccount{}
}
err := SurveyMultipleQuestionWithValidation([]SurveyQuestionWithValidationArgs{
{
Prompt: &survey.Input{
Message: QuestionGkeExistingServiceAccountName,
Default: config.ExistingServiceAccount.Name,
},
Response: &config.ExistingServiceAccount.Name,
Opts: []survey.AskOpt{survey.WithValidator(survey.Required)},
},
{
Prompt: &survey.Input{
Message: QuestionGkeExistingServiceAccountPrivateKey,
Default: config.ExistingServiceAccount.PrivateKey,
},
Response: &config.ExistingServiceAccount.PrivateKey,
Opts: []survey.AskOpt{
survey.WithValidator(survey.Required),
survey.WithValidator(gcp.ValidateStringIsBase64),
},
}})
return err
}
func promptGkeIntegrationNameQuestions(config *gcp.GenerateGkeTfConfigurationArgs) error {
err := SurveyMultipleQuestionWithValidation([]SurveyQuestionWithValidationArgs{
{
Prompt: &survey.Input{Message: QuestionGkeIntegrationName, Default: config.IntegrationName},
Response: &config.IntegrationName,
},
})
return err
}
func promptCustomizeGkeOutputLocation(extraState *GkeGenerateCommandExtraState) error {
err := SurveyQuestionInteractiveOnly(SurveyQuestionWithValidationArgs{
Prompt: &survey.Input{Message: QuestionGkeCustomizeOutputLocation, Default: extraState.Output},
Response: &extraState.Output,
Opts: []survey.AskOpt{survey.WithValidator(validPathExists)},
Required: true,
})
return err
}