-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathresource_cloud_run_service.go
1965 lines (1766 loc) · 71.1 KB
/
resource_cloud_run_service.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 *** AUTO GENERATED CODE ***
//
// ----------------------------------------------------------------------------
//
// 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"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceCloudRunService() *schema.Resource {
return &schema.Resource{
Create: resourceCloudRunServiceCreate,
Read: resourceCloudRunServiceRead,
Update: resourceCloudRunServiceUpdate,
Delete: resourceCloudRunServiceDelete,
Importer: &schema.ResourceImporter{
State: resourceCloudRunServiceImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Update: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"location": {
Type: schema.TypeString,
Required: true,
Description: `The location of the cloud run instance. eg us-central1`,
},
"metadata": {
Type: schema.TypeList,
Required: true,
Description: `Metadata associated with this Service, including name, namespace, labels,
and annotations.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"annotations": {
Type: schema.TypeMap,
Computed: true,
Optional: true,
Description: `Annotations is a key value map stored with a resource that
may be set by external tools to store and retrieve arbitrary metadata. More
info: http://kubernetes.io/docs/user-guide/annotations`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"labels": {
Type: schema.TypeMap,
Computed: true,
Optional: true,
Description: `Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and routes.
More info: http://kubernetes.io/docs/user-guide/labels`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"namespace": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `In Cloud Run the namespace must be equal to either the
project ID or project number.`,
},
"generation": {
Type: schema.TypeInt,
Computed: true,
Description: `A sequence number representing a specific generation of the desired state.`,
},
"resource_version": {
Type: schema.TypeString,
Computed: true,
Description: `An opaque value that represents the internal version of this object that
can be used by clients to determine when objects have changed. May be used
for optimistic concurrency, change detection, and the watch operation on a
resource or set of resources. They may only be valid for a
particular resource or set of resources.
More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency`,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
Description: `SelfLink is a URL representing this object.`,
},
"uid": {
Type: schema.TypeString,
Computed: true,
Description: `UID is a unique id generated by the server on successful creation of a resource and is not
allowed to change on PUT operations.
More info: http://kubernetes.io/docs/user-guide/identifiers#uids`,
},
},
},
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Name must be unique within a namespace, within a Cloud Run region.
Is required when creating resources. Name is primarily intended
for creation idempotence and configuration definition. Cannot be updated.
More info: http://kubernetes.io/docs/user-guide/identifiers#names`,
},
"template": {
Type: schema.TypeList,
Optional: true,
Description: `template holds the latest specification for the Revision to
be stamped out. The template references the container image, and may also
include labels and annotations that should be attached to the Revision.
To correlate a Revision, and/or to force a Revision to be created when the
spec doesn't otherwise change, a nonce label may be provided in the
template metadata. For more details, see:
https://github.com/knative/serving/blob/master/docs/client-conventions.md#associate-modifications-with-revisions
Cloud Run does not currently support referencing a build that is
responsible for materializing the container image from source.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"spec": {
Type: schema.TypeList,
Required: true,
Description: `RevisionSpec holds the desired state of the Revision (from the client).`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"containers": {
Type: schema.TypeList,
Required: true,
Description: `Container defines the unit of execution for this Revision.
In the context of a Revision, we disallow a number of the fields of
this Container, including: name, ports, and volumeMounts.
The runtime contract is documented here:
https://github.com/knative/serving/blob/master/docs/runtime-contract.md`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"image": {
Type: schema.TypeString,
Required: true,
Description: `Docker image name. This is most often a reference to a container located
in the container registry, such as gcr.io/cloudrun/hello
More info: https://kubernetes.io/docs/concepts/containers/images`,
},
"args": {
Type: schema.TypeList,
Optional: true,
Description: `Arguments to the entrypoint.
The docker image's CMD is used if this is not provided.
Variable references $(VAR_NAME) are expanded using the container's
environment. If a variable cannot be resolved, the reference in the input
string will be unchanged. The $(VAR_NAME) syntax can be escaped with a
double $$, ie: $$(VAR_NAME). Escaped references will never be expanded,
regardless of whether the variable exists or not.
More info:
https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"command": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `Entrypoint array. Not executed within a shell.
The docker image's ENTRYPOINT is used if this is not provided.
Variable references $(VAR_NAME) are expanded using the container's
environment. If a variable cannot be resolved, the reference in the input
string will be unchanged. The $(VAR_NAME) syntax can be escaped with a
double $$, ie: $$(VAR_NAME). Escaped references will never be expanded,
regardless of whether the variable exists or not.
More info:
https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"env": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `List of environment variables to set in the container.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Description: `Name of the environment variable.`,
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: `Variable references $(VAR_NAME) are expanded
using the previous defined environment variables in the container and
any route environment variables. If a variable cannot be resolved,
the reference in the input string will be unchanged. The $(VAR_NAME)
syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped
references will never be expanded, regardless of whether the variable
exists or not.
Defaults to "".`,
},
},
},
},
"env_from": {
Type: schema.TypeList,
Optional: true,
Deprecated: "Not supported by Cloud Run fully managed",
ForceNew: true,
Description: `List of sources to populate environment variables in the container.
All invalid keys will be reported as an event when the container is starting.
When a key exists in multiple sources, the value associated with the last source will
take precedence. Values defined by an Env with a duplicate key will take
precedence.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_map_ref": {
Type: schema.TypeList,
Optional: true,
Description: `The ConfigMap to select from.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"local_object_reference": {
Type: schema.TypeList,
Optional: true,
Description: `The ConfigMap to select from.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: `Name of the referent.
More info:
https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names`,
},
},
},
},
"optional": {
Type: schema.TypeBool,
Optional: true,
Description: `Specify whether the ConfigMap must be defined`,
},
},
},
},
"prefix": {
Type: schema.TypeString,
Optional: true,
Description: `An optional identifier to prepend to each key in the ConfigMap.`,
},
"secret_ref": {
Type: schema.TypeList,
Optional: true,
Description: `The Secret to select from.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"local_object_reference": {
Type: schema.TypeList,
Optional: true,
Description: `The Secret to select from.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: `Name of the referent.
More info:
https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names`,
},
},
},
},
"optional": {
Type: schema.TypeBool,
Optional: true,
Description: `Specify whether the Secret must be defined`,
},
},
},
},
},
},
},
"resources": {
Type: schema.TypeList,
Optional: true,
Description: `Compute Resources required by this container. Used to set values such as max memory
More info:
https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"limits": {
Type: schema.TypeMap,
Optional: true,
Description: `Limits describes the maximum amount of compute resources allowed.
The values of the map is string form of the 'quantity' k8s type:
https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"requests": {
Type: schema.TypeMap,
Optional: true,
Description: `Requests describes the minimum amount of compute resources required.
If Requests is omitted for a container, it defaults to Limits if that is
explicitly specified, otherwise to an implementation-defined value.
The values of the map is string form of the 'quantity' k8s type:
https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go`,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"working_dir": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Not supported by Cloud Run fully managed",
ForceNew: true,
Description: `Container's working directory.
If not specified, the container runtime's default will be used, which
might be configured in the container image.`,
},
},
},
},
"container_concurrency": {
Type: schema.TypeInt,
Optional: true,
Description: `ContainerConcurrency specifies the maximum allowed in-flight (concurrent)
requests per container of the Revision. Values are:
- '0' thread-safe, the system should manage the max concurrency. This is
the default value.
- '1' not-thread-safe. Single concurrency
- '2-N' thread-safe, max concurrency of N`,
},
"service_account_name": {
Type: schema.TypeString,
Optional: true,
Description: `Email address of the IAM service account associated with the revision of the
service. The service account represents the identity of the running revision,
and determines what permissions the revision has. If not provided, the revision
will use the project's default service account.`,
},
"serving_state": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Not supported by Cloud Run fully managed",
Description: `ServingState holds a value describing the state the resources
are in for this Revision.
It is expected
that the system will manipulate this based on routability and load.`,
},
},
},
},
"metadata": {
Type: schema.TypeList,
Optional: true,
Description: `Optional metadata for this Revision, including labels and annotations.
Name will be generated by the Configuration. To set minimum instances
for this revision, use the "autoscaling.knative.dev/minScale" annotation
key. To set maximum instances for this revision, use the
"autoscaling.knative.dev/maxScale" annotation key. To set Cloud SQL
connections for the revision, use the "run.googleapis.com/cloudsql-instances"
annotation key.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"annotations": {
Type: schema.TypeMap,
Optional: true,
Description: `Annotations is a key value map stored with a resource that
may be set by external tools to store and retrieve arbitrary metadata. More
info: http://kubernetes.io/docs/user-guide/annotations`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and routes.
More info: http://kubernetes.io/docs/user-guide/labels`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `Name must be unique within a namespace, within a Cloud Run region.
Is required when creating resources. Name is primarily intended
for creation idempotence and configuration definition. Cannot be updated.
More info: http://kubernetes.io/docs/user-guide/identifiers#names`,
},
"namespace": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `In Cloud Run the namespace must be equal to either the
project ID or project number.`,
},
"generation": {
Type: schema.TypeInt,
Computed: true,
Description: `A sequence number representing a specific generation of the desired state.`,
},
"resource_version": {
Type: schema.TypeString,
Computed: true,
Description: `An opaque value that represents the internal version of this object that
can be used by clients to determine when objects have changed. May be used
for optimistic concurrency, change detection, and the watch operation on a
resource or set of resources. They may only be valid for a
particular resource or set of resources.
More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency`,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
Description: `SelfLink is a URL representing this object.`,
},
"uid": {
Type: schema.TypeString,
Computed: true,
Description: `UID is a unique id generated by the server on successful creation of a resource and is not
allowed to change on PUT operations.
More info: http://kubernetes.io/docs/user-guide/identifiers#uids`,
},
},
},
},
},
},
},
"traffic": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `Traffic specifies how to distribute traffic over a collection of Knative Revisions
and Configurations`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"percent": {
Type: schema.TypeInt,
Required: true,
Description: `Percent specifies percent of the traffic to this Revision or Configuration.`,
},
"latest_revision": {
Type: schema.TypeBool,
Optional: true,
Description: `LatestRevision may be optionally provided to indicate that the latest ready
Revision of the Configuration should be used for this traffic target. When
provided LatestRevision must be true if RevisionName is empty; it must be
false when RevisionName is non-empty.`,
},
"revision_name": {
Type: schema.TypeString,
Optional: true,
Description: `RevisionName of a specific revision to which to send this portion of traffic.`,
},
},
},
},
"status": {
Type: schema.TypeList,
Computed: true,
Description: `The current status of the Service.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"conditions": {
Type: schema.TypeList,
Computed: true,
Description: `Array of observed Service Conditions, indicating the current ready state of the service.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"message": {
Type: schema.TypeString,
Computed: true,
Description: `Human readable message indicating details about the current status.`,
},
"reason": {
Type: schema.TypeString,
Computed: true,
Description: `One-word CamelCase reason for the condition's current status.`,
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: `Status of the condition, one of True, False, Unknown.`,
},
"type": {
Type: schema.TypeString,
Computed: true,
Description: `Type of domain mapping condition.`,
},
},
},
},
"latest_created_revision_name": {
Type: schema.TypeString,
Computed: true,
Description: `From ConfigurationStatus. LatestCreatedRevisionName is the last revision that was created
from this Service's Configuration. It might not be ready yet, for that use
LatestReadyRevisionName.`,
},
"latest_ready_revision_name": {
Type: schema.TypeString,
Computed: true,
Description: `From ConfigurationStatus. LatestReadyRevisionName holds the name of the latest Revision
stamped out from this Service's Configuration that has had its "Ready" condition become
"True".`,
},
"observed_generation": {
Type: schema.TypeInt,
Computed: true,
Description: `ObservedGeneration is the 'Generation' of the Route that was last processed by the
controller.
Clients polling for completed reconciliation should poll until observedGeneration =
metadata.generation and the Ready condition's status is True or False.`,
},
"url": {
Type: schema.TypeString,
Computed: true,
Description: `From RouteStatus. URL holds the url that will distribute traffic over the provided traffic
targets. It generally has the form
https://{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app`,
},
},
},
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceCloudRunServiceCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
obj := make(map[string]interface{})
specProp, err := expandCloudRunServiceSpec(nil, d, config)
if err != nil {
return err
} else if !isEmptyValue(reflect.ValueOf(specProp)) {
obj["spec"] = specProp
}
metadataProp, err := expandCloudRunServiceMetadata(d.Get("metadata"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("metadata"); !isEmptyValue(reflect.ValueOf(metadataProp)) && (ok || !reflect.DeepEqual(v, metadataProp)) {
obj["metadata"] = metadataProp
}
obj, err = resourceCloudRunServiceEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{CloudRunBasePath}}serving.knative.dev/v1/namespaces/{{project}}/services")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Service: %#v", obj)
project, err := getProject(d, config)
if err != nil {
return err
}
res, err := sendRequestWithTimeout(config, "POST", project, url, obj, d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error creating Service: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "locations/{{location}}/namespaces/{{project}}/services/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating Service %q: %#v", d.Id(), res)
return resourceCloudRunServiceRead(d, meta)
}
func resourceCloudRunServiceRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
url, err := replaceVars(d, config, "{{CloudRunBasePath}}serving.knative.dev/v1/namespaces/{{project}}/services/{{name}}")
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
res, err := sendRequest(config, "GET", project, url, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("CloudRunService %q", d.Id()))
}
res, err = resourceCloudRunServiceDecoder(d, meta, res)
if err != nil {
return err
}
if res == nil {
// Decoding the object has resulted in it being gone. It may be marked deleted
log.Printf("[DEBUG] Removing CloudRunService because it no longer exists.")
d.SetId("")
return nil
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Service: %s", err)
}
// Terraform must set the top level schema field, but since this object contains collapsed properties
// it's difficult to know what the top level should be. Instead we just loop over the map returned from flatten.
if flattenedProp := flattenCloudRunServiceSpec(res["spec"], d); flattenedProp != nil {
casted := flattenedProp.([]interface{})[0]
if casted != nil {
for k, v := range casted.(map[string]interface{}) {
d.Set(k, v)
}
}
}
if err := d.Set("status", flattenCloudRunServiceStatus(res["status"], d)); err != nil {
return fmt.Errorf("Error reading Service: %s", err)
}
if err := d.Set("metadata", flattenCloudRunServiceMetadata(res["metadata"], d)); err != nil {
return fmt.Errorf("Error reading Service: %s", err)
}
return nil
}
func resourceCloudRunServiceUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
obj := make(map[string]interface{})
specProp, err := expandCloudRunServiceSpec(nil, d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("spec"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, specProp)) {
obj["spec"] = specProp
}
metadataProp, err := expandCloudRunServiceMetadata(d.Get("metadata"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("metadata"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, metadataProp)) {
obj["metadata"] = metadataProp
}
obj, err = resourceCloudRunServiceEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{CloudRunBasePath}}serving.knative.dev/v1/namespaces/{{project}}/services/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating Service %q: %#v", d.Id(), obj)
_, err = sendRequestWithTimeout(config, "PUT", project, url, obj, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return fmt.Errorf("Error updating Service %q: %s", d.Id(), err)
}
return resourceCloudRunServiceRead(d, meta)
}
func resourceCloudRunServiceDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{CloudRunBasePath}}serving.knative.dev/v1/namespaces/{{project}}/services/{{name}}")
if err != nil {
return err
}
var obj map[string]interface{}
log.Printf("[DEBUG] Deleting Service %q", d.Id())
res, err := sendRequestWithTimeout(config, "DELETE", project, url, obj, d.Timeout(schema.TimeoutDelete))
if err != nil {
return handleNotFoundError(err, d, "Service")
}
log.Printf("[DEBUG] Finished deleting Service %q: %#v", d.Id(), res)
return nil
}
func resourceCloudRunServiceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{
"locations/(?P<location>[^/]+)/namespaces/(?P<project>[^/]+)/services/(?P<name>[^/]+)",
"(?P<location>[^/]+)/(?P<project>[^/]+)/(?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, "locations/{{location}}/namespaces/{{project}}/services/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenCloudRunServiceSpec(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["traffic"] =
flattenCloudRunServiceSpecTraffic(original["traffic"], d)
transformed["template"] =
flattenCloudRunServiceSpecTemplate(original["template"], d)
return []interface{}{transformed}
}
func flattenCloudRunServiceSpecTraffic(v interface{}, d *schema.ResourceData) 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{}{
"revision_name": flattenCloudRunServiceSpecTrafficRevisionName(original["revisionName"], d),
"percent": flattenCloudRunServiceSpecTrafficPercent(original["percent"], d),
"latest_revision": flattenCloudRunServiceSpecTrafficLatestRevision(original["latestRevision"], d),
})
}
return transformed
}
func flattenCloudRunServiceSpecTrafficRevisionName(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTrafficPercent(v interface{}, d *schema.ResourceData) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}
func flattenCloudRunServiceSpecTrafficLatestRevision(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplate(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["metadata"] =
flattenCloudRunServiceSpecTemplateMetadata(original["metadata"], d)
transformed["spec"] =
flattenCloudRunServiceSpecTemplateSpec(original["spec"], d)
return []interface{}{transformed}
}
func flattenCloudRunServiceSpecTemplateMetadata(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["labels"] =
flattenCloudRunServiceSpecTemplateMetadataLabels(original["labels"], d)
transformed["generation"] =
flattenCloudRunServiceSpecTemplateMetadataGeneration(original["generation"], d)
transformed["resource_version"] =
flattenCloudRunServiceSpecTemplateMetadataResourceVersion(original["resourceVersion"], d)
transformed["self_link"] =
flattenCloudRunServiceSpecTemplateMetadataSelfLink(original["selfLink"], d)
transformed["uid"] =
flattenCloudRunServiceSpecTemplateMetadataUid(original["uid"], d)
transformed["namespace"] =
flattenCloudRunServiceSpecTemplateMetadataNamespace(original["namespace"], d)
transformed["annotations"] =
flattenCloudRunServiceSpecTemplateMetadataAnnotations(original["annotations"], d)
transformed["name"] =
flattenCloudRunServiceSpecTemplateMetadataName(original["name"], d)
return []interface{}{transformed}
}
func flattenCloudRunServiceSpecTemplateMetadataLabels(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateMetadataGeneration(v interface{}, d *schema.ResourceData) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}
func flattenCloudRunServiceSpecTemplateMetadataResourceVersion(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateMetadataSelfLink(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateMetadataUid(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateMetadataNamespace(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateMetadataAnnotations(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateMetadataName(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateSpec(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["containers"] =
flattenCloudRunServiceSpecTemplateSpecContainers(original["containers"], d)
transformed["container_concurrency"] =
flattenCloudRunServiceSpecTemplateSpecContainerConcurrency(original["containerConcurrency"], d)
transformed["service_account_name"] =
flattenCloudRunServiceSpecTemplateSpecServiceAccountName(original["serviceAccountName"], d)
transformed["serving_state"] =
flattenCloudRunServiceSpecTemplateSpecServingState(original["servingState"], d)
return []interface{}{transformed}
}
func flattenCloudRunServiceSpecTemplateSpecContainers(v interface{}, d *schema.ResourceData) 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{}{
"working_dir": flattenCloudRunServiceSpecTemplateSpecContainersWorkingDir(original["workingDir"], d),
"args": flattenCloudRunServiceSpecTemplateSpecContainersArgs(original["args"], d),
"env_from": flattenCloudRunServiceSpecTemplateSpecContainersEnvFrom(original["envFrom"], d),
"image": flattenCloudRunServiceSpecTemplateSpecContainersImage(original["image"], d),
"command": flattenCloudRunServiceSpecTemplateSpecContainersCommand(original["command"], d),
"env": flattenCloudRunServiceSpecTemplateSpecContainersEnv(original["env"], d),
"resources": flattenCloudRunServiceSpecTemplateSpecContainersResources(original["resources"], d),
})
}
return transformed
}
func flattenCloudRunServiceSpecTemplateSpecContainersWorkingDir(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateSpecContainersArgs(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateSpecContainersEnvFrom(v interface{}, d *schema.ResourceData) 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{}{
"prefix": flattenCloudRunServiceSpecTemplateSpecContainersEnvFromPrefix(original["prefix"], d),
"config_map_ref": flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRef(original["configMapRef"], d),
"secret_ref": flattenCloudRunServiceSpecTemplateSpecContainersEnvFromSecretRef(original["secretRef"], d),
})
}
return transformed
}
func flattenCloudRunServiceSpecTemplateSpecContainersEnvFromPrefix(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRef(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["optional"] =
flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRefOptional(original["optional"], d)
transformed["local_object_reference"] =
flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRefLocalObjectReference(original["localObjectReference"], d)
return []interface{}{transformed}
}
func flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRefOptional(v interface{}, d *schema.ResourceData) interface{} {
return v
}
func flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRefLocalObjectReference(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})
transformed["name"] =
flattenCloudRunServiceSpecTemplateSpecContainersEnvFromConfigMapRefLocalObjectReferenceName(original["name"], d)
return []interface{}{transformed}