forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_vertex_ai_endpoint.go
966 lines (861 loc) · 39.9 KB
/
resource_vertex_ai_endpoint.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
// ----------------------------------------------------------------------------
//
// *** 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 resourceVertexAIEndpoint() *schema.Resource {
return &schema.Resource{
Create: resourceVertexAIEndpointCreate,
Read: resourceVertexAIEndpointRead,
Update: resourceVertexAIEndpointUpdate,
Delete: resourceVertexAIEndpointDelete,
Importer: &schema.ResourceImporter{
State: resourceVertexAIEndpointImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"display_name": {
Type: schema.TypeString,
Required: true,
Description: `Required. The display name of the Endpoint. The name can be up to 128 characters long and can consist of any UTF-8 characters.`,
},
"location": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The location for the resource`,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The resource name of the Endpoint. The name must be numeric with no leading zeros and can be at most 10 digits.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `The description of the Endpoint.`,
},
"encryption_spec": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `Customer-managed encryption key spec for an Endpoint. If set, this Endpoint and all sub-resources of this Endpoint will be secured by this key.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: 'projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key'. The key needs to be in the same region as where the compute resource is created.`,
},
},
},
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `The labels with user-defined metadata to organize your Endpoints. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"network": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The full name of the Google Compute Engine [network](https://cloud.google.com//compute/docs/networks-and-firewalls#networks) to which the Endpoint should be peered. Private services access must already be configured for the network. If left unspecified, the Endpoint is not peered with any network. Only one of the fields, network or enable_private_service_connect, can be set. [Format](https://cloud.google.com/compute/docs/reference/rest/v1/networks/insert): 'projects/{project}/global/networks/{network}'. Where '{project}' is a project number, as in '12345', and '{network}' is network name.`,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Timestamp when this Endpoint was created.`,
},
"deployed_models": {
Type: schema.TypeList,
Computed: true,
Description: `Output only. The models deployed in this Endpoint. To add or remove DeployedModels use EndpointService.DeployModel and EndpointService.UndeployModel respectively. Models can also be deployed and undeployed using the [Cloud Console](https://console.cloud.google.com/vertex-ai/).`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"automatic_resources": {
Type: schema.TypeList,
Computed: true,
Description: `A description of resources that to large degree are decided by Vertex AI, and require only a modest additional configuration.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"max_replica_count": {
Type: schema.TypeInt,
Computed: true,
Description: `The maximum number of replicas this DeployedModel may be deployed on when the traffic against it increases. If the requested value is too large, the deployment will error, but if deployment succeeds then the ability to scale the model to that many replicas is guaranteed (barring service outages). If traffic against the DeployedModel increases beyond what its replicas at maximum may handle, a portion of the traffic will be dropped. If this value is not provided, a no upper bound for scaling under heavy traffic will be assume, though Vertex AI may be unable to scale beyond certain replica number.`,
},
"min_replica_count": {
Type: schema.TypeInt,
Computed: true,
Description: `The minimum number of replicas this DeployedModel will be always deployed on. If traffic against it increases, it may dynamically be deployed onto more replicas up to max_replica_count, and as traffic decreases, some of these extra replicas may be freed. If the requested value is too large, the deployment will error.`,
},
},
},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Timestamp when the DeployedModel was created.`,
},
"dedicated_resources": {
Type: schema.TypeList,
Computed: true,
Description: `A description of resources that are dedicated to the DeployedModel, and that need a higher degree of manual configuration.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"autoscaling_metric_specs": {
Type: schema.TypeList,
Computed: true,
Description: `The metric specifications that overrides a resource utilization metric (CPU utilization, accelerator's duty cycle, and so on) target value (default to 60 if not set). At most one entry is allowed per metric. If machine_spec.accelerator_count is above 0, the autoscaling will be based on both CPU utilization and accelerator's duty cycle metrics and scale up when either metrics exceeds its target value while scale down if both metrics are under their target value. The default target value is 60 for both metrics. If machine_spec.accelerator_count is 0, the autoscaling will be based on CPU utilization metric only with default target value 60 if not explicitly set. For example, in the case of Online Prediction, if you want to override target CPU utilization to 80, you should set autoscaling_metric_specs.metric_name to 'aiplatform.googleapis.com/prediction/online/cpu/utilization' and autoscaling_metric_specs.target to '80'.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"metric_name": {
Type: schema.TypeString,
Computed: true,
Description: `The resource metric name. Supported metrics: * For Online Prediction: * 'aiplatform.googleapis.com/prediction/online/accelerator/duty_cycle' * 'aiplatform.googleapis.com/prediction/online/cpu/utilization'`,
},
"target": {
Type: schema.TypeInt,
Computed: true,
Description: `The target resource utilization in percentage (1% - 100%) for the given metric; once the real usage deviates from the target by a certain percentage, the machine replicas change. The default value is 60 (representing 60%) if not provided.`,
},
},
},
},
"machine_spec": {
Type: schema.TypeList,
Computed: true,
Description: `The specification of a single machine used by the prediction.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"accelerator_count": {
Type: schema.TypeInt,
Computed: true,
Description: `The number of accelerators to attach to the machine.`,
},
"accelerator_type": {
Type: schema.TypeString,
Computed: true,
Description: `The type of accelerator(s) that may be attached to the machine as per accelerator_count. See possible values [here](https://cloud.google.com/vertex-ai/docs/reference/rest/v1/MachineSpec#AcceleratorType).`,
},
"machine_type": {
Type: schema.TypeString,
Computed: true,
Description: `The type of the machine. See the [list of machine types supported for prediction](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types) See the [list of machine types supported for custom training](https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types). For DeployedModel this field is optional, and the default value is 'n1-standard-2'. For BatchPredictionJob or as part of WorkerPoolSpec this field is required. TODO(rsurowka): Try to better unify the required vs optional.`,
},
},
},
},
"max_replica_count": {
Type: schema.TypeInt,
Computed: true,
Description: `The maximum number of replicas this DeployedModel may be deployed on when the traffic against it increases. If the requested value is too large, the deployment will error, but if deployment succeeds then the ability to scale the model to that many replicas is guaranteed (barring service outages). If traffic against the DeployedModel increases beyond what its replicas at maximum may handle, a portion of the traffic will be dropped. If this value is not provided, will use min_replica_count as the default value. The value of this field impacts the charge against Vertex CPU and GPU quotas. Specifically, you will be charged for max_replica_count * number of cores in the selected machine type) and (max_replica_count * number of GPUs per replica in the selected machine type).`,
},
"min_replica_count": {
Type: schema.TypeInt,
Computed: true,
Description: `The minimum number of machine replicas this DeployedModel will be always deployed on. This value must be greater than or equal to 1. If traffic against the DeployedModel increases, it may dynamically be deployed onto more replicas, and as traffic decreases, some of these extra replicas may be freed.`,
},
},
},
},
"display_name": {
Type: schema.TypeString,
Computed: true,
Description: `The display name of the DeployedModel. If not provided upon creation, the Model's display_name is used.`,
},
"enable_access_logging": {
Type: schema.TypeBool,
Computed: true,
Description: `These logs are like standard server access logs, containing information like timestamp and latency for each prediction request. Note that Stackdriver logs may incur a cost, especially if your project receives prediction requests at a high queries per second rate (QPS). Estimate your costs before enabling this option.`,
},
"enable_container_logging": {
Type: schema.TypeBool,
Computed: true,
Description: `If true, the container of the DeployedModel instances will send 'stderr' and 'stdout' streams to Stackdriver Logging. Only supported for custom-trained Models and AutoML Tabular Models.`,
},
"id": {
Type: schema.TypeString,
Computed: true,
Description: `The ID of the DeployedModel. If not provided upon deployment, Vertex AI will generate a value for this ID. This value should be 1-10 characters, and valid characters are /[0-9]/.`,
},
"model": {
Type: schema.TypeString,
Computed: true,
Description: `The name of the Model that this is the deployment of. Note that the Model may be in a different location than the DeployedModel's Endpoint.`,
},
"model_version_id": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The version ID of the model that is deployed.`,
},
"private_endpoints": {
Type: schema.TypeList,
Computed: true,
Description: `Output only. Provide paths for users to send predict/explain/health requests directly to the deployed model services running on Cloud via private services access. This field is populated if network is configured.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"explain_http_uri": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Http(s) path to send explain requests.`,
},
"health_http_uri": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Http(s) path to send health check requests.`,
},
"predict_http_uri": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Http(s) path to send prediction requests.`,
},
"service_attachment": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The name of the service attachment resource. Populated if private service connect is enabled.`,
},
},
},
},
"service_account": {
Type: schema.TypeString,
Computed: true,
Description: `The service account that the DeployedModel's container runs as. Specify the email address of the service account. If this service account is not specified, the container runs as a service account that doesn't have access to the resource project. Users deploying the Model must have the 'iam.serviceAccounts.actAs' permission on this service account.`,
},
"shared_resources": {
Type: schema.TypeString,
Computed: true,
Description: `The resource name of the shared DeploymentResourcePool to deploy on. Format: projects/{project}/locations/{location}/deploymentResourcePools/{deployment_resource_pool}`,
},
},
},
},
"etag": {
Type: schema.TypeString,
Computed: true,
Description: `Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.`,
},
"model_deployment_monitoring_job": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Resource name of the Model Monitoring job associated with this Endpoint if monitoring is enabled by CreateModelDeploymentMonitoringJob. Format: 'projects/{project}/locations/{location}/modelDeploymentMonitoringJobs/{model_deployment_monitoring_job}'`,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Timestamp when this Endpoint was last updated.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}
func resourceVertexAIEndpointCreate(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{})
displayNameProp, err := expandVertexAIEndpointDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
descriptionProp, err := expandVertexAIEndpointDescription(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
}
labelsProp, err := expandVertexAIEndpointLabels(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
}
encryptionSpecProp, err := expandVertexAIEndpointEncryptionSpec(d.Get("encryption_spec"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("encryption_spec"); !isEmptyValue(reflect.ValueOf(encryptionSpecProp)) && (ok || !reflect.DeepEqual(v, encryptionSpecProp)) {
obj["encryptionSpec"] = encryptionSpecProp
}
networkProp, err := expandVertexAIEndpointNetwork(d.Get("network"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("network"); !isEmptyValue(reflect.ValueOf(networkProp)) && (ok || !reflect.DeepEqual(v, networkProp)) {
obj["network"] = networkProp
}
url, err := replaceVars(d, config, "{{VertexAIBasePath}}projects/{{project}}/locations/{{location}}/endpoints?endpointId={{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Endpoint: %#v", obj)
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Endpoint: %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 Endpoint: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{location}}/endpoints/{{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 = vertexAIOperationWaitTimeWithResponse(
config, res, &opRes, project, "Creating Endpoint", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create Endpoint: %s", err)
}
// This may have caused the ID to update - update it if so.
id, err = replaceVars(d, config, "projects/{{project}}/locations/{{location}}/endpoints/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating Endpoint %q: %#v", d.Id(), res)
return resourceVertexAIEndpointRead(d, meta)
}
func resourceVertexAIEndpointRead(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, "{{VertexAIBasePath}}projects/{{project}}/locations/{{location}}/endpoints/{{name}}")
if err != nil {
return err
}
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Endpoint: %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("VertexAIEndpoint %q", d.Id()))
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("display_name", flattenVertexAIEndpointDisplayName(res["displayName"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("description", flattenVertexAIEndpointDescription(res["description"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("deployed_models", flattenVertexAIEndpointDeployedModels(res["deployedModels"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("labels", flattenVertexAIEndpointLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("create_time", flattenVertexAIEndpointCreateTime(res["createTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("update_time", flattenVertexAIEndpointUpdateTime(res["updateTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("encryption_spec", flattenVertexAIEndpointEncryptionSpec(res["encryptionSpec"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("network", flattenVertexAIEndpointNetwork(res["network"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
if err := d.Set("model_deployment_monitoring_job", flattenVertexAIEndpointModelDeploymentMonitoringJob(res["modelDeploymentMonitoringJob"], d, config)); err != nil {
return fmt.Errorf("Error reading Endpoint: %s", err)
}
return nil
}
func resourceVertexAIEndpointUpdate(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 Endpoint: %s", err)
}
billingProject = project
obj := make(map[string]interface{})
displayNameProp, err := expandVertexAIEndpointDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
descriptionProp, err := expandVertexAIEndpointDescription(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
}
labelsProp, err := expandVertexAIEndpointLabels(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, "{{VertexAIBasePath}}projects/{{project}}/locations/{{location}}/endpoints/{{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating Endpoint %q: %#v", d.Id(), obj)
updateMask := []string{}
if d.HasChange("display_name") {
updateMask = append(updateMask, "displayName")
}
if d.HasChange("description") {
updateMask = append(updateMask, "description")
}
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 Endpoint %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating Endpoint %q: %#v", d.Id(), res)
}
return resourceVertexAIEndpointRead(d, meta)
}
func resourceVertexAIEndpointDelete(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 Endpoint: %s", err)
}
billingProject = project
url, err := replaceVars(d, config, "{{VertexAIBasePath}}projects/{{project}}/locations/{{location}}/endpoints/{{name}}")
if err != nil {
return err
}
var obj map[string]interface{}
log.Printf("[DEBUG] Deleting Endpoint %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, "Endpoint")
}
err = vertexAIOperationWaitTime(
config, res, project, "Deleting Endpoint", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting Endpoint %q: %#v", d.Id(), res)
return nil
}
func resourceVertexAIEndpointImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{
"projects/(?P<project>[^/]+)/locations/(?P<location>[^/]+)/endpoints/(?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}}/endpoints/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenVertexAIEndpointDisplayName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModels(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return v
}
l := v.([]interface{})
transformed := make([]interface{}, 0, len(l))
for _, raw := range l {
original := raw.(map[string]interface{})
if len(original) < 1 {
// Do not include empty json objects coming back from the api
continue
}
transformed = append(transformed, map[string]interface{}{
"dedicated_resources": flattenVertexAIEndpointDeployedModelsDedicatedResources(original["dedicatedResources"], d, config),
"automatic_resources": flattenVertexAIEndpointDeployedModelsAutomaticResources(original["automaticResources"], d, config),
"id": flattenVertexAIEndpointDeployedModelsId(original["id"], d, config),
"model": flattenVertexAIEndpointDeployedModelsModel(original["model"], d, config),
"model_version_id": flattenVertexAIEndpointDeployedModelsModelVersionId(original["modelVersionId"], d, config),
"display_name": flattenVertexAIEndpointDeployedModelsDisplayName(original["displayName"], d, config),
"create_time": flattenVertexAIEndpointDeployedModelsCreateTime(original["createTime"], d, config),
"service_account": flattenVertexAIEndpointDeployedModelsServiceAccount(original["serviceAccount"], d, config),
"enable_access_logging": flattenVertexAIEndpointDeployedModelsEnableAccessLogging(original["enableAccessLogging"], d, config),
"private_endpoints": flattenVertexAIEndpointDeployedModelsPrivateEndpoints(original["privateEndpoints"], d, config),
"shared_resources": flattenVertexAIEndpointDeployedModelsSharedResources(original["sharedResources"], d, config),
"enable_container_logging": flattenVertexAIEndpointDeployedModelsEnableContainerLogging(original["enableContainerLogging"], d, config),
})
}
return transformed
}
func flattenVertexAIEndpointDeployedModelsDedicatedResources(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["machine_spec"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpec(original["machineSpec"], d, config)
transformed["min_replica_count"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesMinReplicaCount(original["minReplicaCount"], d, config)
transformed["max_replica_count"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesMaxReplicaCount(original["maxReplicaCount"], d, config)
transformed["autoscaling_metric_specs"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesAutoscalingMetricSpecs(original["autoscalingMetricSpecs"], d, config)
return []interface{}{transformed}
}
func flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpec(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["machine_type"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpecMachineType(original["machineType"], d, config)
transformed["accelerator_type"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpecAcceleratorType(original["acceleratorType"], d, config)
transformed["accelerator_count"] =
flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpecAcceleratorCount(original["acceleratorCount"], d, config)
return []interface{}{transformed}
}
func flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpecMachineType(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpecAcceleratorType(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsDedicatedResourcesMachineSpecAcceleratorCount(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 flattenVertexAIEndpointDeployedModelsDedicatedResourcesMinReplicaCount(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 flattenVertexAIEndpointDeployedModelsDedicatedResourcesMaxReplicaCount(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 flattenVertexAIEndpointDeployedModelsDedicatedResourcesAutoscalingMetricSpecs(v interface{}, d *schema.ResourceData, config *Config) interface{} {
if v == nil {
return v
}
l := v.([]interface{})
transformed := make([]interface{}, 0, len(l))
for _, raw := range l {
original := raw.(map[string]interface{})
if len(original) < 1 {
// Do not include empty json objects coming back from the api
continue
}
transformed = append(transformed, map[string]interface{}{
"metric_name": flattenVertexAIEndpointDeployedModelsDedicatedResourcesAutoscalingMetricSpecsMetricName(original["metricName"], d, config),
"target": flattenVertexAIEndpointDeployedModelsDedicatedResourcesAutoscalingMetricSpecsTarget(original["target"], d, config),
})
}
return transformed
}
func flattenVertexAIEndpointDeployedModelsDedicatedResourcesAutoscalingMetricSpecsMetricName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsDedicatedResourcesAutoscalingMetricSpecsTarget(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 flattenVertexAIEndpointDeployedModelsAutomaticResources(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["min_replica_count"] =
flattenVertexAIEndpointDeployedModelsAutomaticResourcesMinReplicaCount(original["minReplicaCount"], d, config)
transformed["max_replica_count"] =
flattenVertexAIEndpointDeployedModelsAutomaticResourcesMaxReplicaCount(original["maxReplicaCount"], d, config)
return []interface{}{transformed}
}
func flattenVertexAIEndpointDeployedModelsAutomaticResourcesMinReplicaCount(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 flattenVertexAIEndpointDeployedModelsAutomaticResourcesMaxReplicaCount(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 flattenVertexAIEndpointDeployedModelsId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsModel(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsModelVersionId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsDisplayName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsCreateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsServiceAccount(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsEnableAccessLogging(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsPrivateEndpoints(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["predict_http_uri"] =
flattenVertexAIEndpointDeployedModelsPrivateEndpointsPredictHttpUri(original["predictHttpUri"], d, config)
transformed["explain_http_uri"] =
flattenVertexAIEndpointDeployedModelsPrivateEndpointsExplainHttpUri(original["explainHttpUri"], d, config)
transformed["health_http_uri"] =
flattenVertexAIEndpointDeployedModelsPrivateEndpointsHealthHttpUri(original["healthHttpUri"], d, config)
transformed["service_attachment"] =
flattenVertexAIEndpointDeployedModelsPrivateEndpointsServiceAttachment(original["serviceAttachment"], d, config)
return []interface{}{transformed}
}
func flattenVertexAIEndpointDeployedModelsPrivateEndpointsPredictHttpUri(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsPrivateEndpointsExplainHttpUri(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsPrivateEndpointsHealthHttpUri(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsPrivateEndpointsServiceAttachment(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsSharedResources(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointDeployedModelsEnableContainerLogging(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointLabels(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointCreateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointUpdateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointEncryptionSpec(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["kms_key_name"] =
flattenVertexAIEndpointEncryptionSpecKmsKeyName(original["kmsKeyName"], d, config)
return []interface{}{transformed}
}
func flattenVertexAIEndpointEncryptionSpecKmsKeyName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointNetwork(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenVertexAIEndpointModelDeploymentMonitoringJob(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func expandVertexAIEndpointDisplayName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandVertexAIEndpointDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandVertexAIEndpointLabels(v interface{}, d TerraformResourceData, config *Config) (map[string]string, error) {
if v == nil {
return map[string]string{}, nil
}
m := make(map[string]string)
for k, val := range v.(map[string]interface{}) {
m[k] = val.(string)
}
return m, nil
}
func expandVertexAIEndpointEncryptionSpec(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
l := v.([]interface{})
if len(l) == 0 || l[0] == nil {
return nil, nil
}
raw := l[0]
original := raw.(map[string]interface{})
transformed := make(map[string]interface{})
transformedKmsKeyName, err := expandVertexAIEndpointEncryptionSpecKmsKeyName(original["kms_key_name"], d, config)
if err != nil {
return nil, err
} else if val := reflect.ValueOf(transformedKmsKeyName); val.IsValid() && !isEmptyValue(val) {
transformed["kmsKeyName"] = transformedKmsKeyName
}
return transformed, nil
}
func expandVertexAIEndpointEncryptionSpecKmsKeyName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandVertexAIEndpointNetwork(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}