-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
resource_apigee_instance.go
499 lines (433 loc) · 17.2 KB
/
resource_apigee_instance.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
// ----------------------------------------------------------------------------
//
// *** 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"
)
// Supress diffs when the lists of project have the same number of entries to handle the case that
// API does not return what the user originally provided. Instead, API does some transformation.
// For example, user provides a list of project number, but API returns a list of project Id.
func projectListDiffSuppress(_, _, _ string, d *schema.ResourceData) bool {
return projectListDiffSuppressFunc(d)
}
func projectListDiffSuppressFunc(d TerraformResourceDataChange) bool {
kLength := "consumer_accept_list.#"
oldLength, newLength := d.GetChange(kLength)
oldInt, ok := oldLength.(int)
if !ok {
return false
}
newInt, ok := newLength.(int)
if !ok {
return false
}
log.Printf("[DEBUG] - suppressing diff with oldInt %d, newInt %d", oldInt, newInt)
return oldInt == newInt
}
func resourceApigeeInstance() *schema.Resource {
return &schema.Resource{
Create: resourceApigeeInstanceCreate,
Read: resourceApigeeInstanceRead,
Delete: resourceApigeeInstanceDelete,
Importer: &schema.ResourceImporter{
State: resourceApigeeInstanceImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"location": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Required. Compute Engine location where the instance resides.`,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Resource ID of the instance.`,
},
"org_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The Apigee Organization associated with the Apigee instance,
in the format 'organizations/{{org_name}}'.`,
},
"consumer_accept_list": {
Type: schema.TypeList,
Computed: true,
Optional: true,
ForceNew: true,
DiffSuppressFunc: projectListDiffSuppress,
Description: `Optional. Customer accept list represents the list of projects (id/number) on customer
side that can privately connect to the service attachment. It is an optional field
which the customers can provide during the instance creation. By default, the customer
project associated with the Apigee organization will be included to the list.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Description of the instance.`,
},
"disk_encryption_key_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Customer Managed Encryption Key (CMEK) used for disk and volume encryption. Required for Apigee paid subscriptions only.
Use the following format: 'projects/([^/]+)/locations/([^/]+)/keyRings/([^/]+)/cryptoKeys/([^/]+)'`,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Display name of the instance.`,
},
"ip_range": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `IP range represents the customer-provided CIDR block of length 22 that will be used for
the Apigee instance creation. This optional range, if provided, should be freely
available as part of larger named range the customer has allocated to the Service
Networking peering. If this is not provided, Apigee will automatically request for any
available /22 CIDR block from Service Networking. The customer should use this CIDR block
for configuring their firewall needs to allow traffic from Apigee.
Input format: "a.b.c.d/22"`,
},
"peering_cidr_range": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
Description: `The size of the CIDR block range that will be reserved by the instance. For valid values,
see [CidrRange](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.instances#CidrRange) on the documentation.`,
},
"host": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Hostname or IP address of the exposed Apigee endpoint used by clients to connect to the service.`,
},
"port": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Port number of the exposed Apigee endpoint.`,
},
"service_attachment": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Resource name of the service attachment created for the instance in
the format: projects/*/regions/*/serviceAttachments/* Apigee customers can privately
forward traffic to this service attachment using the PSC endpoints.`,
},
},
UseJSONNumber: true,
}
}
func resourceApigeeInstanceCreate(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 := expandApigeeInstanceName(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
}
locationProp, err := expandApigeeInstanceLocation(d.Get("location"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("location"); !isEmptyValue(reflect.ValueOf(locationProp)) && (ok || !reflect.DeepEqual(v, locationProp)) {
obj["location"] = locationProp
}
peeringCidrRangeProp, err := expandApigeeInstancePeeringCidrRange(d.Get("peering_cidr_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("peering_cidr_range"); !isEmptyValue(reflect.ValueOf(peeringCidrRangeProp)) && (ok || !reflect.DeepEqual(v, peeringCidrRangeProp)) {
obj["peeringCidrRange"] = peeringCidrRangeProp
}
ipRangeProp, err := expandApigeeInstanceIpRange(d.Get("ip_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("ip_range"); !isEmptyValue(reflect.ValueOf(ipRangeProp)) && (ok || !reflect.DeepEqual(v, ipRangeProp)) {
obj["ipRange"] = ipRangeProp
}
descriptionProp, err := expandApigeeInstanceDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
displayNameProp, err := expandApigeeInstanceDisplayName(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
}
diskEncryptionKeyNameProp, err := expandApigeeInstanceDiskEncryptionKeyName(d.Get("disk_encryption_key_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("disk_encryption_key_name"); !isEmptyValue(reflect.ValueOf(diskEncryptionKeyNameProp)) && (ok || !reflect.DeepEqual(v, diskEncryptionKeyNameProp)) {
obj["diskEncryptionKeyName"] = diskEncryptionKeyNameProp
}
consumerAcceptListProp, err := expandApigeeInstanceConsumerAcceptList(d.Get("consumer_accept_list"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("consumer_accept_list"); !isEmptyValue(reflect.ValueOf(consumerAcceptListProp)) && (ok || !reflect.DeepEqual(v, consumerAcceptListProp)) {
obj["consumerAcceptList"] = consumerAcceptListProp
}
lockName, err := replaceVars(d, config, "{{org_id}}/apigeeInstances")
if err != nil {
return err
}
mutexKV.Lock(lockName)
defer mutexKV.Unlock(lockName)
url, err := replaceVars(d, config, "{{ApigeeBasePath}}{{org_id}}/instances")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Instance: %#v", obj)
billingProject := ""
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate), isApigeeRetryableError)
if err != nil {
return fmt.Errorf("Error creating Instance: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "{{org_id}}/instances/{{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 = apigeeOperationWaitTimeWithResponse(
config, res, &opRes, "Creating Instance", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create Instance: %s", err)
}
if err := d.Set("name", flattenApigeeInstanceName(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, "{{org_id}}/instances/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating Instance %q: %#v", d.Id(), res)
return resourceApigeeInstanceRead(d, meta)
}
func resourceApigeeInstanceRead(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, "{{ApigeeBasePath}}{{org_id}}/instances/{{name}}")
if err != nil {
return err
}
billingProject := ""
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil, isApigeeRetryableError)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("ApigeeInstance %q", d.Id()))
}
if err := d.Set("name", flattenApigeeInstanceName(res["name"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("location", flattenApigeeInstanceLocation(res["location"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("peering_cidr_range", flattenApigeeInstancePeeringCidrRange(res["peeringCidrRange"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("description", flattenApigeeInstanceDescription(res["description"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("display_name", flattenApigeeInstanceDisplayName(res["displayName"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("disk_encryption_key_name", flattenApigeeInstanceDiskEncryptionKeyName(res["diskEncryptionKeyName"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("host", flattenApigeeInstanceHost(res["host"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("port", flattenApigeeInstancePort(res["port"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("consumer_accept_list", flattenApigeeInstanceConsumerAcceptList(res["consumerAcceptList"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("service_attachment", flattenApigeeInstanceServiceAttachment(res["serviceAttachment"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
return nil
}
func resourceApigeeInstanceDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
billingProject := ""
lockName, err := replaceVars(d, config, "{{org_id}}/apigeeInstances")
if err != nil {
return err
}
mutexKV.Lock(lockName)
defer mutexKV.Unlock(lockName)
url, err := replaceVars(d, config, "{{ApigeeBasePath}}{{org_id}}/instances/{{name}}")
if err != nil {
return err
}
var obj map[string]interface{}
log.Printf("[DEBUG] Deleting Instance %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), isApigeeRetryableError)
if err != nil {
return handleNotFoundError(err, d, "Instance")
}
err = apigeeOperationWaitTime(
config, res, "Deleting Instance", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting Instance %q: %#v", d.Id(), res)
return nil
}
func resourceApigeeInstanceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
// current import_formats cannot import fields with forward slashes in their value
if err := parseImportId([]string{"(?P<name>.+)"}, d, config); err != nil {
return nil, err
}
nameParts := strings.Split(d.Get("name").(string), "/")
if len(nameParts) == 4 {
// `organizations/{{org_name}}/instances/{{name}}`
orgId := fmt.Sprintf("organizations/%s", nameParts[1])
if err := d.Set("org_id", orgId); err != nil {
return nil, fmt.Errorf("Error setting org_id: %s", err)
}
if err := d.Set("name", nameParts[3]); err != nil {
return nil, fmt.Errorf("Error setting name: %s", err)
}
} else if len(nameParts) == 3 {
// `organizations/{{org_name}}/{{name}}`
orgId := fmt.Sprintf("organizations/%s", nameParts[1])
if err := d.Set("org_id", orgId); err != nil {
return nil, fmt.Errorf("Error setting org_id: %s", err)
}
if err := d.Set("name", nameParts[2]); err != nil {
return nil, fmt.Errorf("Error setting name: %s", err)
}
} else {
return nil, fmt.Errorf(
"Saw %s when the name is expected to have shape %s or %s",
d.Get("name"),
"organizations/{{org_name}}/instances/{{name}}",
"organizations/{{org_name}}/{{name}}")
}
// Replace import id for the resource id
id, err := replaceVars(d, config, "{{org_id}}/instances/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenApigeeInstanceName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceLocation(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstancePeeringCidrRange(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceDisplayName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceDiskEncryptionKeyName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceHost(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstancePort(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceConsumerAcceptList(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func flattenApigeeInstanceServiceAttachment(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}
func expandApigeeInstanceName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstanceLocation(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstancePeeringCidrRange(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstanceIpRange(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstanceDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstanceDisplayName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstanceDiskEncryptionKeyName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
func expandApigeeInstanceConsumerAcceptList(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}