forked from hashicorp/terraform-provider-google-beta
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresource_clouddeploy_automation.go
1608 lines (1425 loc) · 64.6 KB
/
resource_clouddeploy_automation.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// This code is generated by Magic Modules using the following:
//
// Configuration: https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/products/clouddeploy/Automation.yaml
// Template: https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/templates/terraform/resource.go.tmpl
//
// DO NOT EDIT this file directly. Any changes made to this file will be
// overwritten during the next generation cycle.
//
// ----------------------------------------------------------------------------
package clouddeploy
import (
"fmt"
"log"
"net/http"
"reflect"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/verify"
)
func ResourceClouddeployAutomation() *schema.Resource {
return &schema.Resource{
Create: resourceClouddeployAutomationCreate,
Read: resourceClouddeployAutomationRead,
Update: resourceClouddeployAutomationUpdate,
Delete: resourceClouddeployAutomationDelete,
Importer: &schema.ResourceImporter{
State: resourceClouddeployAutomationImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
CustomizeDiff: customdiff.All(
tpgresource.SetAnnotationsDiff,
tpgresource.SetLabelsDiff,
tpgresource.DefaultProviderProject,
),
Schema: map[string]*schema.Schema{
"delivery_pipeline": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The delivery_pipeline for the resource`,
},
"location": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The location for the resource`,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Name of the 'Automation'.`,
},
"rules": {
Type: schema.TypeList,
Required: true,
Description: `Required. List of Automation rules associated with the Automation resource. Must have at least one rule and limited to 250 rules per Delivery Pipeline. Note: the order of the rules here is not the same as the order of execution.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"advance_rollout_rule": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. The 'AdvanceRolloutRule' will automatically advance a successful Rollout.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
Description: `Required. ID of the rule. This id must be unique in the 'Automation' resource to which this rule belongs. The format is 'a-z{0,62}'.`,
},
"source_phases": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Proceeds only after phase name matched any one in the list. This value must consist of lower-case letters, numbers, and hyphens, start with a letter and end with a letter or a number, and have a max length of 63 characters. In other words, it must match the following regex: '^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$'.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"wait": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. How long to wait after a rollout is finished.`,
},
},
},
},
"promote_release_rule": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. 'PromoteReleaseRule' will automatically promote a release from the current target to a specified target.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
Description: `Required. ID of the rule. This id must be unique in the 'Automation' resource to which this rule belongs. The format is 'a-z{0,62}'.`,
},
"destination_phase": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The starting phase of the rollout created by this operation. Default to the first phase.`,
},
"destination_target_id": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The ID of the stage in the pipeline to which this 'Release' is deploying. If unspecified, default it to the next stage in the promotion flow. The value of this field could be one of the following: * The last segment of a target name. It only needs the ID to determine if the target is one of the stages in the promotion sequence defined in the pipeline. * "@next", the next target in the promotion sequence.`,
},
"wait": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. How long the release need to be paused until being promoted to the next target.`,
},
},
},
},
"repair_rollout_rule": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. The RepairRolloutRule will automatically repair a failed rollout.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
Description: `Required. ID of the rule. This id must be unique in the 'Automation' resource to which this rule belongs. The format is 'a-z{0,62}'.`,
},
"jobs": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Jobs to repair. Proceeds only after job name matched any one in the list, or for all jobs if unspecified or empty. The phase that includes the job must match the phase ID specified in sourcePhase. This value must consist of lower-case letters, numbers, and hyphens, start with a letter and end with a letter or a number, and have a max length of 63 characters. In other words, it must match the following regex: ^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"phases": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Phases within which jobs are subject to automatic repair actions on failure. Proceeds only after phase name matched any one in the list, or for all phases if unspecified. This value must consist of lower-case letters, numbers, and hyphens, start with a letter and end with a letter or a number, and have a max length of 63 characters. In other words, it must match the following regex: ^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"repair_phases": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Proceeds only after phase name matched any one in the list. This value must consist of lower-case letters, numbers, and hyphens, start with a letter and end with a letter or a number, and have a max length of 63 characters. In other words, it must match the following regex: '^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$'.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"retry": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Retries a failed job.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attempts": {
Type: schema.TypeString,
Required: true,
Description: `Required. Total number of retries. Retry is skipped if set to 0; The minimum value is 1, and the maximum value is 10.`,
},
"backoff_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: verify.ValidateEnum([]string{"BACKOFF_MODE_UNSPECIFIED", "BACKOFF_MODE_LINEAR", "BACKOFF_MODE_EXPONENTIAL", ""}),
Description: `Optional. The pattern of how wait time will be increased. Default is linear. Backoff mode will be ignored if wait is 0. Possible values: ["BACKOFF_MODE_UNSPECIFIED", "BACKOFF_MODE_LINEAR", "BACKOFF_MODE_EXPONENTIAL"]`,
},
"wait": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. How long to wait for the first retry. Default is 0, and the maximum value is 14d. A duration in seconds with up to nine fractional digits, ending with 's'. Example: '3.5s'.`,
},
},
},
},
"rollback": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Rolls back a Rollout.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination_phase": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The starting phase ID for the Rollout. If unspecified, the Rollout will start in the stable phase.`,
},
"disable_rollback_if_rollout_pending": {
Type: schema.TypeBool,
Optional: true,
Description: `Optional. If pending rollout exists on the target, the rollback operation will be aborted.`,
},
},
},
},
},
},
},
},
},
},
"timed_promote_release_rule": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. The 'TimedPromoteReleaseRule' will automatically promote a release from the current target(s) to the specified target(s) on a configured schedule.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
Description: `Required. ID of the rule. This id must be unique in the 'Automation' resource to which this rule belongs. The format is 'a-z{0,62}'.`,
},
"schedule": {
Type: schema.TypeString,
Required: true,
Description: `Required. Schedule in crontab format. e.g. '0 9 * * 1' for every Monday at 9am.`,
},
"time_zone": {
Type: schema.TypeString,
Required: true,
Description: `Required. The time zone in IANA format IANA Time Zone Database (e.g. America/New_York).`,
},
"destination_phase": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The starting phase of the rollout created by this rule. Default to the first phase.`,
},
"destination_target_id": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The ID of the stage in the pipeline to which this Release is deploying. If unspecified, default it to the next stage in the promotion flow. The value of this field could be one of the following:
- The last segment of a target name
- "@next", the next target in the promotion sequence"`,
},
},
},
},
},
},
},
"selector": {
Type: schema.TypeList,
Required: true,
Description: `Required. Selected resources to which the automation will be applied.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"targets": {
Type: schema.TypeList,
Required: true,
Description: `Contains attributes about a target.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
Description: `ID of the 'Target'. The value of this field could be one of the following: * The last segment of a target name. It only needs the ID to determine which target is being referred to * "*", all targets in a location.`,
},
"labels": {
Type: schema.TypeMap,
Computed: true,
Optional: true,
Description: `Target labels.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
},
},
"service_account": {
Type: schema.TypeString,
Required: true,
Description: `Required. Email address of the user-managed IAM service account that creates Cloud Deploy release and rollout resources.`,
},
"annotations": {
Type: schema.TypeMap,
Optional: true,
Description: `Optional. User annotations. These attributes can only be set and used by the user, and not by Cloud Deploy. Annotations must meet the following constraints: * Annotations are key/value pairs. * Valid annotation keys have two segments: an optional prefix and name, separated by a slash ('/'). * The name segment is required and must be 63 characters or less, beginning and ending with an alphanumeric character ('[a-z0-9A-Z]') with dashes ('-'), underscores ('_'), dots ('.'), and alphanumerics between. * The prefix is optional. If specified, the prefix must be a DNS subdomain: a series of DNS labels separated by dots('.'), not longer than 253 characters in total, followed by a slash ('/'). See https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/#syntax-and-character-set for more details.
**Note**: This field is non-authoritative, and will only manage the annotations present in your configuration.
Please refer to the field 'effective_annotations' for all of the annotations present on the resource.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. Description of the 'Automation'. Max length is 255 characters.`,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `Optional. Labels are attributes that can be set and used by both the user and by Cloud Deploy. Labels must meet the following constraints: * Keys and values can contain only lowercase letters, numeric characters, underscores, and dashes. * All characters must use UTF-8 encoding, and international characters are allowed. * Keys must start with a lowercase letter or international character. * Each resource is limited to a maximum of 64 labels. Both keys and values are additionally constrained to be <= 63 characters.
**Note**: This field is non-authoritative, and will only manage the labels present in your configuration.
Please refer to the field 'effective_labels' for all of the labels present on the resource.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"suspended": {
Type: schema.TypeBool,
Optional: true,
Description: `Optional. When Suspended, automation is deactivated from execution.`,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Time at which the automation was created.`,
},
"effective_annotations": {
Type: schema.TypeMap,
Computed: true,
Description: `All of annotations (key/value pairs) present on the resource in GCP, including the annotations configured through Terraform, other clients and services.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"effective_labels": {
Type: schema.TypeMap,
Computed: true,
Description: `All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"etag": {
Type: schema.TypeString,
Computed: true,
Description: `Optional. The weak etag of the 'Automation' resource. This checksum is computed by the server based on the value of other fields, and may be sent on update and delete requests to ensure the client has an up-to-date value before proceeding.`,
},
"terraform_labels": {
Type: schema.TypeMap,
Computed: true,
Description: `The combination of labels configured directly on the resource
and default labels configured on the provider.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"uid": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Unique identifier of the 'Automation'.`,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Time at which the automation was updated.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}
func resourceClouddeployAutomationCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
obj := make(map[string]interface{})
descriptionProp, err := expandClouddeployAutomationDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
suspendedProp, err := expandClouddeployAutomationSuspended(d.Get("suspended"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("suspended"); ok || !reflect.DeepEqual(v, suspendedProp) {
obj["suspended"] = suspendedProp
}
serviceAccountProp, err := expandClouddeployAutomationServiceAccount(d.Get("service_account"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("service_account"); !tpgresource.IsEmptyValue(reflect.ValueOf(serviceAccountProp)) && (ok || !reflect.DeepEqual(v, serviceAccountProp)) {
obj["serviceAccount"] = serviceAccountProp
}
selectorProp, err := expandClouddeployAutomationSelector(d.Get("selector"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("selector"); !tpgresource.IsEmptyValue(reflect.ValueOf(selectorProp)) && (ok || !reflect.DeepEqual(v, selectorProp)) {
obj["selector"] = selectorProp
}
rulesProp, err := expandClouddeployAutomationRules(d.Get("rules"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("rules"); !tpgresource.IsEmptyValue(reflect.ValueOf(rulesProp)) && (ok || !reflect.DeepEqual(v, rulesProp)) {
obj["rules"] = rulesProp
}
annotationsProp, err := expandClouddeployAutomationEffectiveAnnotations(d.Get("effective_annotations"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_annotations"); !tpgresource.IsEmptyValue(reflect.ValueOf(annotationsProp)) && (ok || !reflect.DeepEqual(v, annotationsProp)) {
obj["annotations"] = annotationsProp
}
labelsProp, err := expandClouddeployAutomationEffectiveLabels(d.Get("effective_labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
url, err := tpgresource.ReplaceVars(d, config, "{{ClouddeployBasePath}}projects/{{project}}/locations/{{location}}/deliveryPipelines/{{delivery_pipeline}}/automations?automationId={{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Automation: %#v", obj)
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Automation: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutCreate),
Headers: headers,
})
if err != nil {
return fmt.Errorf("Error creating Automation: %s", err)
}
// Store the ID now
id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/deliveryPipelines/{{delivery_pipeline}}/automations/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
err = ClouddeployOperationWaitTime(
config, res, project, "Creating Automation", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create Automation: %s", err)
}
log.Printf("[DEBUG] Finished creating Automation %q: %#v", d.Id(), res)
return resourceClouddeployAutomationRead(d, meta)
}
func resourceClouddeployAutomationRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
url, err := tpgresource.ReplaceVars(d, config, "{{ClouddeployBasePath}}projects/{{project}}/locations/{{location}}/deliveryPipelines/{{delivery_pipeline}}/automations/{{name}}")
if err != nil {
return err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Automation: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ClouddeployAutomation %q", d.Id()))
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("uid", flattenClouddeployAutomationUid(res["uid"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("description", flattenClouddeployAutomationDescription(res["description"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("create_time", flattenClouddeployAutomationCreateTime(res["createTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("update_time", flattenClouddeployAutomationUpdateTime(res["updateTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("annotations", flattenClouddeployAutomationAnnotations(res["annotations"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("labels", flattenClouddeployAutomationLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("etag", flattenClouddeployAutomationEtag(res["etag"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("suspended", flattenClouddeployAutomationSuspended(res["suspended"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("service_account", flattenClouddeployAutomationServiceAccount(res["serviceAccount"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("selector", flattenClouddeployAutomationSelector(res["selector"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("rules", flattenClouddeployAutomationRules(res["rules"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("effective_annotations", flattenClouddeployAutomationEffectiveAnnotations(res["annotations"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("terraform_labels", flattenClouddeployAutomationTerraformLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
if err := d.Set("effective_labels", flattenClouddeployAutomationEffectiveLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Automation: %s", err)
}
return nil
}
func resourceClouddeployAutomationUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Automation: %s", err)
}
billingProject = project
obj := make(map[string]interface{})
descriptionProp, err := expandClouddeployAutomationDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
suspendedProp, err := expandClouddeployAutomationSuspended(d.Get("suspended"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("suspended"); ok || !reflect.DeepEqual(v, suspendedProp) {
obj["suspended"] = suspendedProp
}
serviceAccountProp, err := expandClouddeployAutomationServiceAccount(d.Get("service_account"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("service_account"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, serviceAccountProp)) {
obj["serviceAccount"] = serviceAccountProp
}
selectorProp, err := expandClouddeployAutomationSelector(d.Get("selector"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("selector"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, selectorProp)) {
obj["selector"] = selectorProp
}
rulesProp, err := expandClouddeployAutomationRules(d.Get("rules"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("rules"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, rulesProp)) {
obj["rules"] = rulesProp
}
annotationsProp, err := expandClouddeployAutomationEffectiveAnnotations(d.Get("effective_annotations"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_annotations"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, annotationsProp)) {
obj["annotations"] = annotationsProp
}
labelsProp, err := expandClouddeployAutomationEffectiveLabels(d.Get("effective_labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
url, err := tpgresource.ReplaceVars(d, config, "{{ClouddeployBasePath}}projects/{{project}}/locations/{{location}}/deliveryPipelines/{{delivery_pipeline}}/automations/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating Automation %q: %#v", d.Id(), obj)
headers := make(http.Header)
updateMask := []string{}
if d.HasChange("description") {
updateMask = append(updateMask, "description")
}
if d.HasChange("suspended") {
updateMask = append(updateMask, "suspended")
}
if d.HasChange("service_account") {
updateMask = append(updateMask, "serviceAccount")
}
if d.HasChange("selector") {
updateMask = append(updateMask, "selector")
}
if d.HasChange("rules") {
updateMask = append(updateMask, "rules")
}
if d.HasChange("effective_annotations") {
updateMask = append(updateMask, "annotations")
}
if d.HasChange("effective_labels") {
updateMask = append(updateMask, "labels")
}
// updateMask is a URL parameter but not present in the schema, so ReplaceVars
// won't set it
url, err = transport_tpg.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 := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
// if updateMask is empty we are not updating anything so skip the post
if len(updateMask) > 0 {
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "PATCH",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutUpdate),
Headers: headers,
})
if err != nil {
return fmt.Errorf("Error updating Automation %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating Automation %q: %#v", d.Id(), res)
}
err = ClouddeployOperationWaitTime(
config, res, project, "Updating Automation", userAgent,
d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
return resourceClouddeployAutomationRead(d, meta)
}
func resourceClouddeployAutomationDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Automation: %s", err)
}
billingProject = project
url, err := tpgresource.ReplaceVars(d, config, "{{ClouddeployBasePath}}projects/{{project}}/locations/{{location}}/deliveryPipelines/{{delivery_pipeline}}/automations/{{name}}")
if err != nil {
return err
}
var obj map[string]interface{}
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
log.Printf("[DEBUG] Deleting Automation %q", d.Id())
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "DELETE",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutDelete),
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, "Automation")
}
err = ClouddeployOperationWaitTime(
config, res, project, "Deleting Automation", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting Automation %q: %#v", d.Id(), res)
return nil
}
func resourceClouddeployAutomationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*transport_tpg.Config)
if err := tpgresource.ParseImportId([]string{
"^projects/(?P<project>[^/]+)/locations/(?P<location>[^/]+)/deliveryPipelines/(?P<delivery_pipeline>[^/]+)/automations/(?P<name>[^/]+)$",
"^(?P<project>[^/]+)/(?P<location>[^/]+)/(?P<delivery_pipeline>[^/]+)/(?P<name>[^/]+)$",
"^(?P<location>[^/]+)/(?P<delivery_pipeline>[^/]+)/(?P<name>[^/]+)$",
}, d, config); err != nil {
return nil, err
}
// Replace import id for the resource id
id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/deliveryPipelines/{{delivery_pipeline}}/automations/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenClouddeployAutomationUid(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationAnnotations(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return v
}
transformed := make(map[string]interface{})
if l, ok := d.GetOkExists("annotations"); ok {
for k := range l.(map[string]interface{}) {
transformed[k] = v.(map[string]interface{})[k]
}
}
return transformed
}
func flattenClouddeployAutomationLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return v
}
transformed := make(map[string]interface{})
if l, ok := d.GetOkExists("labels"); ok {
for k := range l.(map[string]interface{}) {
transformed[k] = v.(map[string]interface{})[k]
}
}
return transformed
}
func flattenClouddeployAutomationEtag(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationSuspended(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationServiceAccount(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationSelector(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["targets"] =
flattenClouddeployAutomationSelectorTargets(original["targets"], d, config)
return []interface{}{transformed}
}
func flattenClouddeployAutomationSelectorTargets(v interface{}, d *schema.ResourceData, config *transport_tpg.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{}{
"id": flattenClouddeployAutomationSelectorTargetsId(original["id"], d, config),
"labels": flattenClouddeployAutomationSelectorTargetsLabels(original["labels"], d, config),
})
}
return transformed
}
func flattenClouddeployAutomationSelectorTargetsId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationSelectorTargetsLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRules(v interface{}, d *schema.ResourceData, config *transport_tpg.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{}{
"promote_release_rule": flattenClouddeployAutomationRulesPromoteReleaseRule(original["promoteReleaseRule"], d, config),
"advance_rollout_rule": flattenClouddeployAutomationRulesAdvanceRolloutRule(original["advanceRolloutRule"], d, config),
"repair_rollout_rule": flattenClouddeployAutomationRulesRepairRolloutRule(original["repairRolloutRule"], d, config),
"timed_promote_release_rule": flattenClouddeployAutomationRulesTimedPromoteReleaseRule(original["timedPromoteReleaseRule"], d, config),
})
}
return transformed
}
func flattenClouddeployAutomationRulesPromoteReleaseRule(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["id"] =
flattenClouddeployAutomationRulesPromoteReleaseRuleId(original["id"], d, config)
transformed["wait"] =
flattenClouddeployAutomationRulesPromoteReleaseRuleWait(original["wait"], d, config)
transformed["destination_target_id"] =
flattenClouddeployAutomationRulesPromoteReleaseRuleDestinationTargetId(original["destinationTargetId"], d, config)
transformed["destination_phase"] =
flattenClouddeployAutomationRulesPromoteReleaseRuleDestinationPhase(original["destinationPhase"], d, config)
return []interface{}{transformed}
}
func flattenClouddeployAutomationRulesPromoteReleaseRuleId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesPromoteReleaseRuleWait(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesPromoteReleaseRuleDestinationTargetId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesPromoteReleaseRuleDestinationPhase(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesAdvanceRolloutRule(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["id"] =
flattenClouddeployAutomationRulesAdvanceRolloutRuleId(original["id"], d, config)
transformed["wait"] =
flattenClouddeployAutomationRulesAdvanceRolloutRuleWait(original["wait"], d, config)
transformed["source_phases"] =
flattenClouddeployAutomationRulesAdvanceRolloutRuleSourcePhases(original["sourcePhases"], d, config)
return []interface{}{transformed}
}
func flattenClouddeployAutomationRulesAdvanceRolloutRuleId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesAdvanceRolloutRuleWait(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesAdvanceRolloutRuleSourcePhases(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesRepairRolloutRule(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["id"] =
flattenClouddeployAutomationRulesRepairRolloutRuleId(original["id"], d, config)
transformed["phases"] =
flattenClouddeployAutomationRulesRepairRolloutRulePhases(original["phases"], d, config)
transformed["jobs"] =
flattenClouddeployAutomationRulesRepairRolloutRuleJobs(original["jobs"], d, config)
transformed["repair_phases"] =
flattenClouddeployAutomationRulesRepairRolloutRuleRepairPhases(original["repairPhases"], d, config)
return []interface{}{transformed}
}
func flattenClouddeployAutomationRulesRepairRolloutRuleId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenClouddeployAutomationRulesRepairRolloutRulePhases(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v