-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
resource_cloudfunctions2_function.go
2071 lines (1819 loc) · 79.3 KB
/
resource_cloudfunctions2_function.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 resourceCloudfunctions2function() *schema.Resource {
return &schema.Resource{
Create: resourceCloudfunctions2functionCreate,
Read: resourceCloudfunctions2functionRead,
Update: resourceCloudfunctions2functionUpdate,
Delete: resourceCloudfunctions2functionDelete,
Importer: &schema.ResourceImporter{
State: resourceCloudfunctions2functionImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `A user-defined name of the function. Function names must
be unique globally and match pattern 'projects/*/locations/*/functions/*'.`,
},
"build_config": {
Type: schema.TypeList,
Optional: true,
Description: `Describes the Build step of the function that builds a container
from the given source.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"docker_repository": {
Type: schema.TypeString,
Optional: true,
Description: `User managed repository created in Artifact Registry optionally with a customer managed encryption key.`,
},
"entry_point": {
Type: schema.TypeString,
Optional: true,
Description: `The name of the function (as defined in source code) that will be executed.
Defaults to the resource name suffix, if not specified. For backward
compatibility, if function with given name is not found, then the system
will try to use function named "function". For Node.js this is name of a
function exported by the module specified in source_location.`,
},
"environment_variables": {
Type: schema.TypeMap,
Computed: true,
Optional: true,
Description: `User-provided build-time environment variables for the function.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"runtime": {
Type: schema.TypeString,
Optional: true,
Description: `The runtime in which to run the function. Required when deploying a new
function, optional when updating an existing function.`,
},
"source": {
Type: schema.TypeList,
Optional: true,
Description: `The location of the function source code.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"repo_source": {
Type: schema.TypeList,
Optional: true,
Description: `If provided, get the source from this location in a Cloud Source Repository.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"branch_name": {
Type: schema.TypeString,
Optional: true,
Description: `Regex matching branches to build.`,
ExactlyOneOf: []string{},
},
"commit_sha": {
Type: schema.TypeString,
Optional: true,
Description: `Regex matching tags to build.`,
ExactlyOneOf: []string{},
},
"dir": {
Type: schema.TypeString,
Optional: true,
Description: `Directory, relative to the source root, in which to run the build.`,
},
"invert_regex": {
Type: schema.TypeBool,
Optional: true,
Description: `Only trigger a build if the revision regex does
NOT match the revision regex.`,
},
"project_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `ID of the project that owns the Cloud Source Repository. If omitted, the
project ID requesting the build is assumed.`,
},
"repo_name": {
Type: schema.TypeString,
Optional: true,
Description: `Name of the Cloud Source Repository.`,
},
"tag_name": {
Type: schema.TypeString,
Optional: true,
Description: `Regex matching tags to build.`,
ExactlyOneOf: []string{},
},
},
},
ExactlyOneOf: []string{},
},
"storage_source": {
Type: schema.TypeList,
Optional: true,
Description: `If provided, get the source from this location in Google Cloud Storage.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bucket": {
Type: schema.TypeString,
Optional: true,
Description: `Google Cloud Storage bucket containing the source`,
},
"generation": {
Type: schema.TypeInt,
Optional: true,
Description: `Google Cloud Storage generation for the object. If the generation
is omitted, the latest generation will be used.`,
},
"object": {
Type: schema.TypeString,
Optional: true,
Description: `Google Cloud Storage object containing the source.`,
},
},
},
ExactlyOneOf: []string{},
},
},
},
},
"worker_pool": {
Type: schema.TypeString,
Optional: true,
Description: `Name of the Cloud Build Custom Worker Pool that should be used to build the function.`,
},
"build": {
Type: schema.TypeString,
Computed: true,
Description: `The Cloud Build name of the latest successful
deployment of the function.`,
},
},
},
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `User-provided description of a function.`,
},
"event_trigger": {
Type: schema.TypeList,
Optional: true,
Description: `An Eventarc trigger managed by Google Cloud Functions that fires events in
response to a condition in another service.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"event_filters": {
Type: schema.TypeSet,
Optional: true,
Description: `Criteria used to filter events.`,
Elem: cloudfunctions2functionEventTriggerEventFiltersSchema(),
// Default schema.HashSchema is used.
},
"event_type": {
Type: schema.TypeString,
Optional: true,
Description: `Required. The type of event to observe.`,
},
"pubsub_topic": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `The name of a Pub/Sub topic in the same project that will be used
as the transport topic for the event delivery.`,
},
"retry_policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"RETRY_POLICY_UNSPECIFIED", "RETRY_POLICY_DO_NOT_RETRY", "RETRY_POLICY_RETRY", ""}),
Description: `Describes the retry policy in case of function's execution failure.
Retried execution is charged as any other execution. Possible values: ["RETRY_POLICY_UNSPECIFIED", "RETRY_POLICY_DO_NOT_RETRY", "RETRY_POLICY_RETRY"]`,
},
"service_account_email": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `The email of the service account for this function.`,
},
"trigger_region": {
Type: schema.TypeString,
Optional: true,
Description: `The region that the trigger will be in. The trigger will only receive
events originating in this region. It can be the same
region as the function, a different region or multi-region, or the global
region. If not provided, defaults to the same region as the function.`,
},
"trigger": {
Type: schema.TypeString,
Computed: true,
Description: `The resource name of the Eventarc trigger.`,
},
},
},
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `A set of key/value label pairs associated with this Cloud Function.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"location": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The location of this cloud function.`,
},
"service_config": {
Type: schema.TypeList,
Optional: true,
Description: `Describes the Service being deployed.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"all_traffic_on_latest_revision": {
Type: schema.TypeBool,
Optional: true,
Description: `Whether 100% of traffic is routed to the latest revision. Defaults to true.`,
Default: true,
},
"available_memory": {
Type: schema.TypeString,
Optional: true,
Description: `The amount of memory available for a function.
Defaults to 256M. Supported units are k, M, G, Mi, Gi. If no unit is
supplied the value is interpreted as bytes.`,
},
"environment_variables": {
Type: schema.TypeMap,
Optional: true,
Description: `Environment variables that shall be available during function execution.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ingress_settings": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"ALLOW_ALL", "ALLOW_INTERNAL_ONLY", "ALLOW_INTERNAL_AND_GCLB", ""}),
Description: `Available ingress settings. Defaults to "ALLOW_ALL" if unspecified. Default value: "ALLOW_ALL" Possible values: ["ALLOW_ALL", "ALLOW_INTERNAL_ONLY", "ALLOW_INTERNAL_AND_GCLB"]`,
Default: "ALLOW_ALL",
},
"max_instance_count": {
Type: schema.TypeInt,
Optional: true,
Description: `The limit on the maximum number of function instances that may coexist at a
given time.`,
},
"min_instance_count": {
Type: schema.TypeInt,
Optional: true,
Description: `The limit on the minimum number of function instances that may coexist at a
given time.`,
},
"secret_environment_variables": {
Type: schema.TypeList,
Optional: true,
Description: `Secret environment variables configuration.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
Description: `Name of the environment variable.`,
},
"project_id": {
Type: schema.TypeString,
Required: true,
Description: `Project identifier (preferrably project number but can also be the project ID) of the project that contains the secret. If not set, it will be populated with the function's project assuming that the secret exists in the same project as of the function.`,
},
"secret": {
Type: schema.TypeString,
Required: true,
Description: `Name of the secret in secret manager (not the full resource name).`,
},
"version": {
Type: schema.TypeString,
Required: true,
Description: `Version of the secret (version number or the string 'latest'). It is recommended to use a numeric version for secret environment variables as any updates to the secret value is not reflected until new instances start.`,
},
},
},
},
"secret_volumes": {
Type: schema.TypeList,
Optional: true,
Description: `Secret volumes configuration.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mount_path": {
Type: schema.TypeString,
Required: true,
Description: `The path within the container to mount the secret volume. For example, setting the mountPath as /etc/secrets would mount the secret value files under the /etc/secrets directory. This directory will also be completely shadowed and unavailable to mount any other secrets. Recommended mount path: /etc/secrets`,
},
"project_id": {
Type: schema.TypeString,
Required: true,
Description: `Project identifier (preferrably project number but can also be the project ID) of the project that contains the secret. If not set, it will be populated with the function's project assuming that the secret exists in the same project as of the function.`,
},
"secret": {
Type: schema.TypeString,
Required: true,
Description: `Name of the secret in secret manager (not the full resource name).`,
},
"versions": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `List of secret versions to mount for this secret. If empty, the latest version of the secret will be made available in a file named after the secret under the mount point.'`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"path": {
Type: schema.TypeString,
Required: true,
Description: `Relative path of the file under the mount path where the secret value for this version will be fetched and made available. For example, setting the mountPath as '/etc/secrets' and path as secret_foo would mount the secret value file at /etc/secrets/secret_foo.`,
},
"version": {
Type: schema.TypeString,
Required: true,
Description: `Version of the secret (version number or the string 'latest'). It is preferable to use latest version with secret volumes as secret value changes are reflected immediately.`,
},
},
},
},
},
},
},
"service": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `Name of the service associated with a Function.`,
},
"service_account_email": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `The email of the service account for this function.`,
},
"timeout_seconds": {
Type: schema.TypeInt,
Optional: true,
Description: `The function execution timeout. Execution is considered failed and
can be terminated if the function is not completed at the end of the
timeout period. Defaults to 60 seconds.`,
},
"vpc_connector": {
Type: schema.TypeString,
Optional: true,
Description: `The Serverless VPC Access connector that this cloud function can connect to.`,
},
"vpc_connector_egress_settings": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED", "PRIVATE_RANGES_ONLY", "ALL_TRAFFIC", ""}),
Description: `Available egress settings. Possible values: ["VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED", "PRIVATE_RANGES_ONLY", "ALL_TRAFFIC"]`,
},
"gcf_uri": {
Type: schema.TypeString,
Computed: true,
Description: `URIs of the Service deployed`,
},
"uri": {
Type: schema.TypeString,
Computed: true,
Description: `URI of the Service deployed.`,
},
},
},
},
"environment": {
Type: schema.TypeString,
Computed: true,
Description: `The environment the function is hosted on.`,
},
"state": {
Type: schema.TypeString,
Computed: true,
Description: `Describes the current state of the function.`,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Description: `The last update timestamp of a Cloud Function.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}
func cloudfunctions2functionEventTriggerEventFiltersSchema() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"attribute": {
Type: schema.TypeString,
Required: true,
Description: `'Required. The name of a CloudEvents attribute.
Currently, only a subset of attributes are supported for filtering. Use the 'gcloud eventarc providers describe' command to learn more about events and their attributes.
Do not filter for the 'type' attribute here, as this is already achieved by the resource's 'event_type' attribute.`,
},
"value": {
Type: schema.TypeString,
Required: true,
Description: `Required. The value for the attribute.
If the operator field is set as 'match-path-pattern', this value can be a path pattern instead of an exact value.`,
},
"operator": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The operator used for matching the events with the value of
the filter. If not specified, only events that have an exact key-value
pair specified in the filter are matched.
The only allowed value is 'match-path-pattern'.
[See documentation on path patterns here](https://cloud.google.com/eventarc/docs/path-patterns)'`,
},
},
}
}
func resourceCloudfunctions2functionCreate(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{})
nameProp, err := expandCloudfunctions2functionName(d.Get("name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {
obj["name"] = nameProp
}
descriptionProp, err := expandCloudfunctions2functionDescription(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
}
buildConfigProp, err := expandCloudfunctions2functionBuildConfig(d.Get("build_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("build_config"); !isEmptyValue(reflect.ValueOf(buildConfigProp)) && (ok || !reflect.DeepEqual(v, buildConfigProp)) {
obj["buildConfig"] = buildConfigProp
}
serviceConfigProp, err := expandCloudfunctions2functionServiceConfig(d.Get("service_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("service_config"); !isEmptyValue(reflect.ValueOf(serviceConfigProp)) && (ok || !reflect.DeepEqual(v, serviceConfigProp)) {
obj["serviceConfig"] = serviceConfigProp
}
eventTriggerProp, err := expandCloudfunctions2functionEventTrigger(d.Get("event_trigger"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("event_trigger"); !isEmptyValue(reflect.ValueOf(eventTriggerProp)) && (ok || !reflect.DeepEqual(v, eventTriggerProp)) {
obj["eventTrigger"] = eventTriggerProp
}
labelsProp, err := expandCloudfunctions2functionLabels(d.Get("labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
url, err := replaceVars(d, config, "{{Cloudfunctions2BasePath}}projects/{{project}}/locations/{{location}}/functions?functionId={{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new function: %#v", obj)
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for function: %s", err)
}
billingProject = project
// 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 function: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{location}}/functions/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
// Use the resource in the operation response to populate
// identity fields and d.Id() before read
var opRes map[string]interface{}
err = cloudfunctions2OperationWaitTimeWithResponse(
config, res, &opRes, project, "Creating function", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create function: %s", err)
}
if err := d.Set("name", flattenCloudfunctions2functionName(opRes["name"], d, config)); err != nil {
return err
}
// This may have caused the ID to update - update it if so.
id, err = replaceVars(d, config, "projects/{{project}}/locations/{{location}}/functions/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating function %q: %#v", d.Id(), res)
return resourceCloudfunctions2functionRead(d, meta)
}
func resourceCloudfunctions2functionRead(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, "{{Cloudfunctions2BasePath}}projects/{{project}}/locations/{{location}}/functions/{{name}}")
if err != nil {
return err
}
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for function: %s", err)
}
billingProject = project
// 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("Cloudfunctions2function %q", d.Id()))
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("name", flattenCloudfunctions2functionName(res["name"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("description", flattenCloudfunctions2functionDescription(res["description"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("environment", flattenCloudfunctions2functionEnvironment(res["environment"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("state", flattenCloudfunctions2functionState(res["state"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("build_config", flattenCloudfunctions2functionBuildConfig(res["buildConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("service_config", flattenCloudfunctions2functionServiceConfig(res["serviceConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("event_trigger", flattenCloudfunctions2functionEventTrigger(res["eventTrigger"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("update_time", flattenCloudfunctions2functionUpdateTime(res["updateTime"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
if err := d.Set("labels", flattenCloudfunctions2functionLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading function: %s", err)
}
return nil
}
func resourceCloudfunctions2functionUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for function: %s", err)
}
billingProject = project
obj := make(map[string]interface{})
descriptionProp, err := expandCloudfunctions2functionDescription(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
}
buildConfigProp, err := expandCloudfunctions2functionBuildConfig(d.Get("build_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("build_config"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, buildConfigProp)) {
obj["buildConfig"] = buildConfigProp
}
serviceConfigProp, err := expandCloudfunctions2functionServiceConfig(d.Get("service_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("service_config"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, serviceConfigProp)) {
obj["serviceConfig"] = serviceConfigProp
}
eventTriggerProp, err := expandCloudfunctions2functionEventTrigger(d.Get("event_trigger"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("event_trigger"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, eventTriggerProp)) {
obj["eventTrigger"] = eventTriggerProp
}
labelsProp, err := expandCloudfunctions2functionLabels(d.Get("labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
url, err := replaceVars(d, config, "{{Cloudfunctions2BasePath}}projects/{{project}}/locations/{{location}}/functions/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating function %q: %#v", d.Id(), obj)
updateMask := []string{}
if d.HasChange("description") {
updateMask = append(updateMask, "description")
}
if d.HasChange("build_config") {
updateMask = append(updateMask, "buildConfig")
}
if d.HasChange("service_config") {
updateMask = append(updateMask, "serviceConfig")
}
if d.HasChange("event_trigger") {
updateMask = append(updateMask, "eventTrigger")
}
if d.HasChange("labels") {
updateMask = append(updateMask, "labels")
}
// 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 function %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating function %q: %#v", d.Id(), res)
}
err = cloudfunctions2OperationWaitTime(
config, res, project, "Updating function", userAgent,
d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
return resourceCloudfunctions2functionRead(d, meta)
}
func resourceCloudfunctions2functionDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for function: %s", err)
}
billingProject = project
url, err := replaceVars(d, config, "{{Cloudfunctions2BasePath}}projects/{{project}}/locations/{{location}}/functions/{{name}}")
if err != nil {
return err
}
var obj map[string]interface{}
log.Printf("[DEBUG] Deleting function %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, "function")
}
err = cloudfunctions2OperationWaitTime(
config, res, project, "Deleting function", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting function %q: %#v", d.Id(), res)
return nil
}
func resourceCloudfunctions2functionImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{
"projects/(?P<project>[^/]+)/locations/(?P<location>[^/]+)/functions/(?P<name>[^/]+)",
"(?P<project>[^/]+)/(?P<location>[^/]+)/(?P<name>[^/]+)",
"(?P<location>[^/]+)/(?P<name>[^/]+)",
}, d, config); err != nil {
return nil, err
}
// Replace import id for the resource id
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{location}}/functions/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenCloudfunctions2functionName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return v
}
return NameFromSelfLinkStateFunc(v)
}
func flattenCloudfunctions2functionDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionEnvironment(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionState(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfig(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["build"] =
flattenCloudfunctions2functionBuildConfigBuild(original["build"], d, config)
transformed["runtime"] =
flattenCloudfunctions2functionBuildConfigRuntime(original["runtime"], d, config)
transformed["entry_point"] =
flattenCloudfunctions2functionBuildConfigEntryPoint(original["entryPoint"], d, config)
transformed["source"] =
flattenCloudfunctions2functionBuildConfigSource(original["source"], d, config)
transformed["worker_pool"] =
flattenCloudfunctions2functionBuildConfigWorkerPool(original["workerPool"], d, config)
transformed["environment_variables"] =
flattenCloudfunctions2functionBuildConfigEnvironmentVariables(original["environmentVariables"], d, config)
transformed["docker_repository"] =
flattenCloudfunctions2functionBuildConfigDockerRepository(original["dockerRepository"], d, config)
return []interface{}{transformed}
}
func flattenCloudfunctions2functionBuildConfigBuild(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigRuntime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigEntryPoint(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigSource(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["storage_source"] =
flattenCloudfunctions2functionBuildConfigSourceStorageSource(original["storageSource"], d, config)
transformed["repo_source"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSource(original["repoSource"], d, config)
return []interface{}{transformed}
}
func flattenCloudfunctions2functionBuildConfigSourceStorageSource(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["bucket"] =
flattenCloudfunctions2functionBuildConfigSourceStorageSourceBucket(original["bucket"], d, config)
transformed["object"] =
flattenCloudfunctions2functionBuildConfigSourceStorageSourceObject(original["object"], d, config)
transformed["generation"] =
flattenCloudfunctions2functionBuildConfigSourceStorageSourceGeneration(original["generation"], d, config)
return []interface{}{transformed}
}
func flattenCloudfunctions2functionBuildConfigSourceStorageSourceBucket(v interface{}, d *schema.ResourceData, config *Config) interface{} {
// This flatten function is shared between the resource and the datasource.
// TF Input format: {bucket-name}
// GET Response format: gcf-v2-sources-{Project-number}-{location}
// As TF Input and GET response values have different format,
// we will return TF Input value to prevent state drift.
if bVal, ok := d.GetOk("build_config.0.source.0.storage_source.0.bucket"); ok {
return bVal
}
// For the datasource, there is no prior TF Input for this attribute.
// Hence, GET Response value is returned.
return v
}
func flattenCloudfunctions2functionBuildConfigSourceStorageSourceObject(v interface{}, d *schema.ResourceData, config *Config) interface{} {
// This flatten function is shared between the resource and the datasource.
// TF Input format: {object-name}
// GET Response format: {function-name}/{object-name}
// As TF Input and GET response values have different format,
// we will return TF Input value to prevent state drift.
if ObjVal, ok := d.GetOk("build_config.0.source.0.storage_source.0.object"); ok {
return ObjVal
}
// For the datasource, there is no prior TF Input for this attribute.
// Hence, GET Response value is returned.
return v
}
func flattenCloudfunctions2functionBuildConfigSourceStorageSourceGeneration(v interface{}, d *schema.ResourceData, config *Config) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := stringToFixed64(strVal); err == nil {
return intVal
}
}
// number values are represented as float64
if floatVal, ok := v.(float64); ok {
intVal := int(floatVal)
return intVal
}
return v // let terraform core handle it otherwise
}
func flattenCloudfunctions2functionBuildConfigSourceRepoSource(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"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceProjectId(original["projectId"], d, config)
transformed["repo_name"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceRepoName(original["repoName"], d, config)
transformed["branch_name"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceBranchName(original["branchName"], d, config)
transformed["tag_name"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceTagName(original["tagName"], d, config)
transformed["commit_sha"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceCommitSha(original["commitSha"], d, config)
transformed["dir"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceDir(original["dir"], d, config)
transformed["invert_regex"] =
flattenCloudfunctions2functionBuildConfigSourceRepoSourceInvertRegex(original["invertRegex"], d, config)
return []interface{}{transformed}
}
func flattenCloudfunctions2functionBuildConfigSourceRepoSourceProjectId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigSourceRepoSourceRepoName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigSourceRepoSourceBranchName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigSourceRepoSourceTagName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenCloudfunctions2functionBuildConfigSourceRepoSourceCommitSha(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v