forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_data_loss_prevention_job_trigger.go
1971 lines (1753 loc) · 79.4 KB
/
resource_data_loss_prevention_job_trigger.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------
package google
import (
"fmt"
"log"
"reflect"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceDataLossPreventionJobTrigger() *schema.Resource {
return &schema.Resource{
Create: resourceDataLossPreventionJobTriggerCreate,
Read: resourceDataLossPreventionJobTriggerRead,
Update: resourceDataLossPreventionJobTriggerUpdate,
Delete: resourceDataLossPreventionJobTriggerDelete,
Importer: &schema.ResourceImporter{
State: resourceDataLossPreventionJobTriggerImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"parent": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The parent of the trigger, either in the format 'projects/{{project}}'
or 'projects/{{project}}/locations/{{location}}'`,
},
"triggers": {
Type: schema.TypeList,
Required: true,
Description: `What event needs to occur for a new job to be started.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"schedule": {
Type: schema.TypeList,
Optional: true,
Description: `Schedule for triggered jobs`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"recurrence_period_duration": {
Type: schema.TypeString,
Optional: true,
Description: `With this option a job is started a regular periodic basis. For example: every day (86400 seconds).
A scheduled start time will be skipped if the previous execution has not ended when its scheduled time occurs.
This value must be set to a time duration greater than or equal to 1 day and can be no longer than 60 days.
A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".`,
},
},
},
},
},
},
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `A description of the job trigger.`,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: `User set display name of the job trigger.`,
},
"inspect_job": {
Type: schema.TypeList,
Optional: true,
Description: `Controls what and how to inspect for findings.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"actions": {
Type: schema.TypeList,
Required: true,
Description: `A task to execute on the completion of a job.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"pub_sub": {
Type: schema.TypeList,
Optional: true,
Description: `Publish a message into a given Pub/Sub topic when the job completes.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"topic": {
Type: schema.TypeString,
Required: true,
Description: `Cloud Pub/Sub topic to send notifications to.`,
},
},
},
ExactlyOneOf: []string{},
},
"save_findings": {
Type: schema.TypeList,
Optional: true,
Description: `Schedule for triggered jobs`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"output_config": {
Type: schema.TypeList,
Required: true,
Description: `Information on where to store output`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"table": {
Type: schema.TypeList,
Required: true,
Description: `Information on the location of the target BigQuery Table.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dataset_id": {
Type: schema.TypeString,
Required: true,
Description: `Dataset ID of the table.`,
},
"project_id": {
Type: schema.TypeString,
Required: true,
Description: `The Google Cloud Platform project ID of the project containing the table.`,
},
"table_id": {
Type: schema.TypeString,
Optional: true,
Description: `Name of the table. If is not set a new one will be generated for you with the following format:
'dlp_googleapis_yyyy_mm_dd_[dlp_job_id]'. Pacific timezone will be used for generating the date details.`,
},
},
},
},
"output_schema": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"BASIC_COLUMNS", "GCS_COLUMNS", "DATASTORE_COLUMNS", "BIG_QUERY_COLUMNS", "ALL_COLUMNS", ""}),
Description: `Schema used for writing the findings for Inspect jobs. This field is only used for
Inspect and must be unspecified for Risk jobs. Columns are derived from the Finding
object. If appending to an existing table, any columns from the predefined schema
that are missing will be added. No columns in the existing table will be deleted.
If unspecified, then all available columns will be used for a new table or an (existing)
table with no schema, and no changes will be made to an existing table that has a schema.
Only for use with external storage. Possible values: ["BASIC_COLUMNS", "GCS_COLUMNS", "DATASTORE_COLUMNS", "BIG_QUERY_COLUMNS", "ALL_COLUMNS"]`,
},
},
},
},
},
},
ExactlyOneOf: []string{},
},
},
},
},
"inspect_template_name": {
Type: schema.TypeString,
Required: true,
Description: `The name of the template to run when this job is triggered.`,
},
"storage_config": {
Type: schema.TypeList,
Required: true,
Description: `Information on where to inspect`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"big_query_options": {
Type: schema.TypeList,
Optional: true,
Description: `Options defining BigQuery table and row identifiers.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"table_reference": {
Type: schema.TypeList,
Required: true,
Description: `Set of files to scan.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dataset_id": {
Type: schema.TypeString,
Required: true,
Description: `The dataset ID of the table.`,
},
"project_id": {
Type: schema.TypeString,
Required: true,
Description: `The Google Cloud Platform project ID of the project containing the table.`,
},
"table_id": {
Type: schema.TypeString,
Required: true,
Description: `The name of the table.`,
},
},
},
},
"rows_limit": {
Type: schema.TypeInt,
Optional: true,
Description: `Max number of rows to scan. If the table has more rows than this value, the rest of the rows are omitted.
If not set, or if set to 0, all rows will be scanned. Only one of rowsLimit and rowsLimitPercent can be
specified. Cannot be used in conjunction with TimespanConfig.`,
},
"rows_limit_percent": {
Type: schema.TypeInt,
Optional: true,
Description: `Max percentage of rows to scan. The rest are omitted. The number of rows scanned is rounded down.
Must be between 0 and 100, inclusively. Both 0 and 100 means no limit. Defaults to 0. Only one of
rowsLimit and rowsLimitPercent can be specified. Cannot be used in conjunction with TimespanConfig.`,
},
"sample_method": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"TOP", "RANDOM_START", ""}),
Description: `How to sample rows if not all rows are scanned. Meaningful only when used in conjunction with either
rowsLimit or rowsLimitPercent. If not specified, rows are scanned in the order BigQuery reads them. Default value: "TOP" Possible values: ["TOP", "RANDOM_START"]`,
Default: "TOP",
},
},
},
},
"cloud_storage_options": {
Type: schema.TypeList,
Optional: true,
Description: `Options defining a file or a set of files within a Google Cloud Storage bucket.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"file_set": {
Type: schema.TypeList,
Required: true,
Description: `Set of files to scan.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"regex_file_set": {
Type: schema.TypeList,
Optional: true,
Description: `The regex-filtered set of files to scan.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bucket_name": {
Type: schema.TypeString,
Required: true,
Description: `The name of a Cloud Storage bucket.`,
},
"exclude_regex": {
Type: schema.TypeList,
Optional: true,
Description: `A list of regular expressions matching file paths to exclude. All files in the bucket that match at
least one of these regular expressions will be excluded from the scan.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"include_regex": {
Type: schema.TypeList,
Optional: true,
Description: `A list of regular expressions matching file paths to include. All files in the bucket
that match at least one of these regular expressions will be included in the set of files,
except for those that also match an item in excludeRegex. Leaving this field empty will
match all files by default (this is equivalent to including .* in the list)`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
ExactlyOneOf: []string{"inspect_job.0.storage_config.0.cloud_storage_options.0.file_set.0.url", "inspect_job.0.storage_config.0.cloud_storage_options.0.file_set.0.regex_file_set"},
},
"url": {
Type: schema.TypeString,
Optional: true,
Description: `The Cloud Storage url of the file(s) to scan, in the format 'gs://<bucket>/<path>'. Trailing wildcard
in the path is allowed.
If the url ends in a trailing slash, the bucket or directory represented by the url will be scanned
non-recursively (content in sub-directories will not be scanned). This means that 'gs://mybucket/' is
equivalent to 'gs://mybucket/*', and 'gs://mybucket/directory/' is equivalent to 'gs://mybucket/directory/*'.`,
ExactlyOneOf: []string{"inspect_job.0.storage_config.0.cloud_storage_options.0.file_set.0.url", "inspect_job.0.storage_config.0.cloud_storage_options.0.file_set.0.regex_file_set"},
},
},
},
},
"bytes_limit_per_file": {
Type: schema.TypeInt,
Optional: true,
Description: `Max number of bytes to scan from a file. If a scanned file's size is bigger than this value
then the rest of the bytes are omitted.`,
},
"bytes_limit_per_file_percent": {
Type: schema.TypeInt,
Optional: true,
Description: `Max percentage of bytes to scan from a file. The rest are omitted. The number of bytes scanned is rounded down.
Must be between 0 and 100, inclusively. Both 0 and 100 means no limit.`,
},
"file_types": {
Type: schema.TypeList,
Optional: true,
Description: `List of file type groups to include in the scan. If empty, all files are scanned and available data
format processors are applied. In addition, the binary content of the selected files is always scanned as well.
Images are scanned only as binary if the specified region does not support image inspection and no fileTypes were specified. Possible values: ["BINARY_FILE", "TEXT_FILE", "IMAGE", "WORD", "PDF", "AVRO", "CSV", "TSV"]`,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateEnum([]string{"BINARY_FILE", "TEXT_FILE", "IMAGE", "WORD", "PDF", "AVRO", "CSV", "TSV"}),
},
},
"files_limit_percent": {
Type: schema.TypeInt,
Optional: true,
Description: `Limits the number of files to scan to this percentage of the input FileSet. Number of files scanned is rounded down.
Must be between 0 and 100, inclusively. Both 0 and 100 means no limit.`,
},
"sample_method": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"TOP", "RANDOM_START", ""}),
Description: `How to sample bytes if not all bytes are scanned. Meaningful only when used in conjunction with bytesLimitPerFile.
If not specified, scanning would start from the top. Possible values: ["TOP", "RANDOM_START"]`,
},
},
},
},
"datastore_options": {
Type: schema.TypeList,
Optional: true,
Description: `Options defining a data set within Google Cloud Datastore.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kind": {
Type: schema.TypeList,
Required: true,
Description: `A representation of a Datastore kind.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: `The name of the Datastore kind.`,
},
},
},
},
"partition_id": {
Type: schema.TypeList,
Required: true,
Description: `Datastore partition ID. A partition ID identifies a grouping of entities. The grouping
is always by project and namespace, however the namespace ID may be empty.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"project_id": {
Type: schema.TypeString,
Required: true,
Description: `The ID of the project to which the entities belong.`,
},
"namespace_id": {
Type: schema.TypeString,
Optional: true,
Description: `If not empty, the ID of the namespace to which the entities belong.`,
},
},
},
},
},
},
},
"timespan_config": {
Type: schema.TypeList,
Optional: true,
Description: `Information on where to inspect`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"timestamp_field": {
Type: schema.TypeList,
Required: true,
Description: `Information on where to inspect`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: `Specification of the field containing the timestamp of scanned items. Used for data sources like Datastore and BigQuery.
For BigQuery: Required to filter out rows based on the given start and end times. If not specified and the table was
modified between the given start and end times, the entire table will be scanned. The valid data types of the timestamp
field are: INTEGER, DATE, TIMESTAMP, or DATETIME BigQuery column.
For Datastore. Valid data types of the timestamp field are: TIMESTAMP. Datastore entity will be scanned if the
timestamp property does not exist or its value is empty or invalid.`,
},
},
},
},
"enable_auto_population_of_timespan_config": {
Type: schema.TypeBool,
Optional: true,
Description: `When the job is started by a JobTrigger we will automatically figure out a valid startTime to avoid
scanning files that have not been modified since the last time the JobTrigger executed. This will
be based on the time of the execution of the last run of the JobTrigger.`,
},
"end_time": {
Type: schema.TypeString,
Optional: true,
Description: `Exclude files or rows newer than this value. If set to zero, no upper time limit is applied.`,
AtLeastOneOf: []string{"inspect_job.0.storage_config.0.timespan_config.0.start_time", "inspect_job.0.storage_config.0.timespan_config.0.end_time"},
},
"start_time": {
Type: schema.TypeString,
Optional: true,
Description: `Exclude files or rows older than this value.`,
AtLeastOneOf: []string{"inspect_job.0.storage_config.0.timespan_config.0.start_time", "inspect_job.0.storage_config.0.timespan_config.0.end_time"},
},
},
},
},
},
},
},
},
},
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"PAUSED", "HEALTHY", "CANCELLED", ""}),
Description: `Whether the trigger is currently active. Default value: "HEALTHY" Possible values: ["PAUSED", "HEALTHY", "CANCELLED"]`,
Default: "HEALTHY",
},
"last_run_time": {
Type: schema.TypeString,
Computed: true,
Description: `The timestamp of the last time this trigger executed.`,
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: `The resource name of the job trigger. Set by the server.`,
},
},
UseJSONNumber: true,
}
}
func resourceDataLossPreventionJobTriggerCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
obj := make(map[string]interface{})
descriptionProp, err := expandDataLossPreventionJobTriggerDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
displayNameProp, err := expandDataLossPreventionJobTriggerDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
statusProp, err := expandDataLossPreventionJobTriggerStatus(d.Get("status"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("status"); !isEmptyValue(reflect.ValueOf(statusProp)) && (ok || !reflect.DeepEqual(v, statusProp)) {
obj["status"] = statusProp
}
triggersProp, err := expandDataLossPreventionJobTriggerTriggers(d.Get("triggers"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("triggers"); !isEmptyValue(reflect.ValueOf(triggersProp)) && (ok || !reflect.DeepEqual(v, triggersProp)) {
obj["triggers"] = triggersProp
}
inspectJobProp, err := expandDataLossPreventionJobTriggerInspectJob(d.Get("inspect_job"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("inspect_job"); !isEmptyValue(reflect.ValueOf(inspectJobProp)) && (ok || !reflect.DeepEqual(v, inspectJobProp)) {
obj["inspectJob"] = inspectJobProp
}
obj, err = resourceDataLossPreventionJobTriggerEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{DataLossPreventionBasePath}}{{parent}}/jobTriggers")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new JobTrigger: %#v", obj)
billingProject := ""
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error creating JobTrigger: %s", err)
}
if err := d.Set("name", flattenDataLossPreventionJobTriggerName(res["name"], d, config)); err != nil {
return fmt.Errorf(`Error setting computed identity field "name": %s`, err)
}
// Store the ID now
id, err := replaceVars(d, config, "{{parent}}/jobTriggers/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating JobTrigger %q: %#v", d.Id(), res)
return resourceDataLossPreventionJobTriggerRead(d, meta)
}
func resourceDataLossPreventionJobTriggerRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{DataLossPreventionBasePath}}{{parent}}/jobTriggers/{{name}}")
if err != nil {
return err
}
billingProject := ""
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("DataLossPreventionJobTrigger %q", d.Id()))
}
if err := d.Set("name", flattenDataLossPreventionJobTriggerName(res["name"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
if err := d.Set("description", flattenDataLossPreventionJobTriggerDescription(res["description"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
if err := d.Set("display_name", flattenDataLossPreventionJobTriggerDisplayName(res["displayName"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
if err := d.Set("last_run_time", flattenDataLossPreventionJobTriggerLastRunTime(res["lastRunTime"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
if err := d.Set("status", flattenDataLossPreventionJobTriggerStatus(res["status"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
if err := d.Set("triggers", flattenDataLossPreventionJobTriggerTriggers(res["triggers"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
if err := d.Set("inspect_job", flattenDataLossPreventionJobTriggerInspectJob(res["inspectJob"], d, config)); err != nil {
return fmt.Errorf("Error reading JobTrigger: %s", err)
}
return nil
}
func resourceDataLossPreventionJobTriggerUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
billingProject := ""
obj := make(map[string]interface{})
descriptionProp, err := expandDataLossPreventionJobTriggerDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
displayNameProp, err := expandDataLossPreventionJobTriggerDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
statusProp, err := expandDataLossPreventionJobTriggerStatus(d.Get("status"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("status"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, statusProp)) {
obj["status"] = statusProp
}
triggersProp, err := expandDataLossPreventionJobTriggerTriggers(d.Get("triggers"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("triggers"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, triggersProp)) {
obj["triggers"] = triggersProp
}
inspectJobProp, err := expandDataLossPreventionJobTriggerInspectJob(d.Get("inspect_job"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("inspect_job"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, inspectJobProp)) {
obj["inspectJob"] = inspectJobProp
}
obj, err = resourceDataLossPreventionJobTriggerEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{DataLossPreventionBasePath}}{{parent}}/jobTriggers/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating JobTrigger %q: %#v", d.Id(), obj)
updateMask := []string{}
if d.HasChange("description") {
updateMask = append(updateMask, "description")
}
if d.HasChange("display_name") {
updateMask = append(updateMask, "displayName")
}
if d.HasChange("status") {
updateMask = append(updateMask, "status")
}
if d.HasChange("triggers") {
updateMask = append(updateMask, "triggers")
}
if d.HasChange("inspect_job") {
updateMask = append(updateMask, "inspectJob")
}
// updateMask is a URL parameter but not present in the schema, so replaceVars
// won't set it
url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
if err != nil {
return err
}
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return fmt.Errorf("Error updating JobTrigger %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating JobTrigger %q: %#v", d.Id(), res)
}
return resourceDataLossPreventionJobTriggerRead(d, meta)
}
func resourceDataLossPreventionJobTriggerDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
billingProject := ""
url, err := replaceVars(d, config, "{{DataLossPreventionBasePath}}{{parent}}/jobTriggers/{{name}}")
if err != nil {
return err
}
var obj map[string]interface{}
log.Printf("[DEBUG] Deleting JobTrigger %q", d.Id())
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete))
if err != nil {
return handleNotFoundError(err, d, "JobTrigger")
}
log.Printf("[DEBUG] Finished deleting JobTrigger %q: %#v", d.Id(), res)
return nil
}
func resourceDataLossPreventionJobTriggerImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
// Custom import to handle parent possibilities
if err := parseImportId([]string{"(?P<name>.+)"}, d, config); err != nil {
return nil, err
}
parts := strings.Split(d.Get("name").(string), "/")
if len(parts) == 6 {
if err := d.Set("name", parts[5]); err != nil {
return nil, fmt.Errorf("Error setting name: %s", err)
}
} else if len(parts) == 4 {
if err := d.Set("name", parts[3]); err != nil {
return nil, fmt.Errorf("Error setting name: %s", err)
}
} else {
return nil, fmt.Errorf("Unexpected import id: %s, expected form {{parent}}/jobTrigger/{{name}}", d.Get("name").(string))
}
// Remove "/jobTrigger/{{name}}" from the id
parts = parts[:len(parts)-2]
if err := d.Set("parent", strings.Join(parts, "/")); err != nil {
return nil, fmt.Errorf("Error setting parent: %s", err)
}
// Replace import id for the resource id
id, err := replaceVars(d, config, "{{parent}}/jobTriggers/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenDataLossPreventionJobTriggerName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return v
}
return NameFromSelfLinkStateFunc(v)
}
func flattenDataLossPreventionJobTriggerDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerDisplayName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerLastRunTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerStatus(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerTriggers(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return v
}
l := v.([]interface{})
transformed := make([]interface{}, 0, len(l))
for _, raw := range l {
original := raw.(map[string]interface{})
if len(original) < 1 {
// Do not include empty json objects coming back from the api
continue
}
transformed = append(transformed, map[string]interface{}{
"schedule": flattenDataLossPreventionJobTriggerTriggersSchedule(original["schedule"], d, config),
})
}
return transformed
}
func flattenDataLossPreventionJobTriggerTriggersSchedule(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["recurrence_period_duration"] =
flattenDataLossPreventionJobTriggerTriggersScheduleRecurrencePeriodDuration(original["recurrencePeriodDuration"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerTriggersScheduleRecurrencePeriodDuration(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJob(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["inspect_template_name"] =
flattenDataLossPreventionJobTriggerInspectJobInspectTemplateName(original["inspectTemplateName"], d, config)
transformed["storage_config"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfig(original["storageConfig"], d, config)
transformed["actions"] =
flattenDataLossPreventionJobTriggerInspectJobActions(original["actions"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobInspectTemplateName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfig(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["timespan_config"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfig(original["timespanConfig"], d, config)
transformed["datastore_options"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptions(original["datastoreOptions"], d, config)
transformed["cloud_storage_options"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptions(original["cloudStorageOptions"], d, config)
transformed["big_query_options"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigBigQueryOptions(original["bigQueryOptions"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfig(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["start_time"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigStartTime(original["startTime"], d, config)
transformed["end_time"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigEndTime(original["endTime"], d, config)
transformed["enable_auto_population_of_timespan_config"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigEnableAutoPopulationOfTimespanConfig(original["enableAutoPopulationOfTimespanConfig"], d, config)
transformed["timestamp_field"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigTimestampField(original["timestampField"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigStartTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigEndTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigEnableAutoPopulationOfTimespanConfig(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigTimestampField(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["name"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigTimestampFieldName(original["name"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigTimespanConfigTimestampFieldName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptions(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["partition_id"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsPartitionId(original["partitionId"], d, config)
transformed["kind"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsKind(original["kind"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsPartitionId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["project_id"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsPartitionIdProjectId(original["projectId"], d, config)
transformed["namespace_id"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsPartitionIdNamespaceId(original["namespaceId"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsPartitionIdProjectId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsPartitionIdNamespaceId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsKind(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["name"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsKindName(original["name"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigDatastoreOptionsKindName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptions(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["file_set"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsFileSet(original["fileSet"], d, config)
transformed["bytes_limit_per_file"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsBytesLimitPerFile(original["bytesLimitPerFile"], d, config)
transformed["bytes_limit_per_file_percent"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsBytesLimitPerFilePercent(original["bytesLimitPerFilePercent"], d, config)
transformed["files_limit_percent"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsFilesLimitPercent(original["filesLimitPercent"], d, config)
transformed["file_types"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsFileTypes(original["fileTypes"], d, config)
transformed["sample_method"] =
flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsSampleMethod(original["sampleMethod"], d, config)
return []interface{}{transformed}
}
func flattenDataLossPreventionJobTriggerInspectJobStorageConfigCloudStorageOptionsFileSet(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}