forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
field_helpers.go
442 lines (366 loc) · 15.4 KB
/
field_helpers.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
package google
import (
"fmt"
"regexp"
)
const (
globalLinkTemplate = "projects/%s/global/%s/%s"
globalLinkBasePattern = "projects/(.+)/global/%s/(.+)"
zonalLinkTemplate = "projects/%s/zones/%s/%s/%s"
zonalLinkBasePattern = "projects/(.+)/zones/(.+)/%s/(.+)"
zonalPartialLinkBasePattern = "zones/(.+)/%s/(.+)"
regionalLinkTemplate = "projects/%s/regions/%s/%s/%s"
regionalLinkBasePattern = "projects/(.+)/regions/(.+)/%s/(.+)"
regionalPartialLinkBasePattern = "regions/(.+)/%s/(.+)"
projectLinkTemplate = "projects/%s/%s/%s"
projectBasePattern = "projects/(.+)/%s/(.+)"
organizationLinkTemplate = "organizations/%s/%s/%s"
organizationBasePattern = "organizations/(.+)/%s/(.+)"
)
// ------------------------------------------------------------
// Field helpers
// ------------------------------------------------------------
func ParseNetworkFieldValue(network string, d TerraformResourceData, config *Config) (*GlobalFieldValue, error) {
return parseGlobalFieldValue("networks", network, "project", d, config, true)
}
func ParseSubnetworkFieldValue(subnetwork string, d TerraformResourceData, config *Config) (*RegionalFieldValue, error) {
return parseRegionalFieldValue("subnetworks", subnetwork, "project", "region", "zone", d, config, true)
}
func ParseSubnetworkFieldValueWithProjectField(subnetwork, projectField string, d TerraformResourceData, config *Config) (*RegionalFieldValue, error) {
return parseRegionalFieldValue("subnetworks", subnetwork, projectField, "region", "zone", d, config, true)
}
func ParseSslCertificateFieldValue(sslCertificate string, d TerraformResourceData, config *Config) (*GlobalFieldValue, error) {
return parseGlobalFieldValue("sslCertificates", sslCertificate, "project", d, config, false)
}
func ParseHttpHealthCheckFieldValue(healthCheck string, d TerraformResourceData, config *Config) (*GlobalFieldValue, error) {
return parseGlobalFieldValue("httpHealthChecks", healthCheck, "project", d, config, false)
}
func ParseDiskFieldValue(disk string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) {
return parseZonalFieldValue("disks", disk, "project", "zone", d, config, false)
}
func ParseRegionDiskFieldValue(disk string, d TerraformResourceData, config *Config) (*RegionalFieldValue, error) {
return parseRegionalFieldValue("disks", disk, "project", "region", "zone", d, config, false)
}
func ParseOrganizationCustomRoleName(role string) (*OrganizationFieldValue, error) {
return parseOrganizationFieldValue("roles", role, false)
}
func ParseAcceleratorFieldValue(accelerator string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) {
return parseZonalFieldValue("acceleratorTypes", accelerator, "project", "zone", d, config, false)
}
func ParseMachineTypesFieldValue(machineType string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) {
return parseZonalFieldValue("machineTypes", machineType, "project", "zone", d, config, false)
}
func ParseInstanceFieldValue(instance string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) {
return parseZonalFieldValue("instances", instance, "project", "zone", d, config, false)
}
func ParseInstanceGroupFieldValue(instanceGroup string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) {
return parseZonalFieldValue("instanceGroups", instanceGroup, "project", "zone", d, config, false)
}
func ParseInstanceTemplateFieldValue(instanceTemplate string, d TerraformResourceData, config *Config) (*GlobalFieldValue, error) {
return parseGlobalFieldValue("instanceTemplates", instanceTemplate, "project", d, config, false)
}
func ParseMachineImageFieldValue(machineImage string, d TerraformResourceData, config *Config) (*GlobalFieldValue, error) {
return parseGlobalFieldValue("machineImages", machineImage, "project", d, config, false)
}
func ParseSecurityPolicyFieldValue(securityPolicy string, d TerraformResourceData, config *Config) (*GlobalFieldValue, error) {
return parseGlobalFieldValue("securityPolicies", securityPolicy, "project", d, config, true)
}
func ParseNetworkEndpointGroupFieldValue(networkEndpointGroup string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) {
return parseZonalFieldValue("networkEndpointGroups", networkEndpointGroup, "project", "zone", d, config, false)
}
func ParseNetworkEndpointGroupRegionalFieldValue(networkEndpointGroup string, d TerraformResourceData, config *Config) (*RegionalFieldValue, error) {
return parseRegionalFieldValue("networkEndpointGroups", networkEndpointGroup, "project", "region", "zone", d, config, false)
}
// ------------------------------------------------------------
// Base helpers used to create helpers for specific fields.
// ------------------------------------------------------------
type GlobalFieldValue struct {
Project string
Name string
resourceType string
}
func (f GlobalFieldValue) RelativeLink() string {
if len(f.Name) == 0 {
return ""
}
return fmt.Sprintf(globalLinkTemplate, f.Project, f.resourceType, f.Name)
}
// Parses a global field supporting 5 different formats:
// - https://www.googleapis.com/compute/ANY_VERSION/projects/{my_project}/global/{resource_type}/{resource_name}
// - projects/{my_project}/global/{resource_type}/{resource_name}
// - global/{resource_type}/{resource_name}
// - resource_name
// - "" (empty string). RelativeLink() returns empty if isEmptyValid is true.
//
// If the project is not specified, it first tries to get the project from the `projectSchemaField` and then fallback on the default project.
func parseGlobalFieldValue(resourceType, fieldValue, projectSchemaField string, d TerraformResourceData, config *Config, isEmptyValid bool) (*GlobalFieldValue, error) {
if len(fieldValue) == 0 {
if isEmptyValid {
return &GlobalFieldValue{resourceType: resourceType}, nil
}
return nil, fmt.Errorf("The global field for resource %s cannot be empty", resourceType)
}
r := regexp.MustCompile(fmt.Sprintf(globalLinkBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &GlobalFieldValue{
Project: parts[1],
Name: parts[2],
resourceType: resourceType,
}, nil
}
project, err := getProjectFromSchema(projectSchemaField, d, config)
if err != nil {
return nil, err
}
return &GlobalFieldValue{
Project: project,
Name: GetResourceNameFromSelfLink(fieldValue),
resourceType: resourceType,
}, nil
}
type ZonalFieldValue struct {
Project string
Zone string
Name string
resourceType string
}
func (f ZonalFieldValue) RelativeLink() string {
if len(f.Name) == 0 {
return ""
}
return fmt.Sprintf(zonalLinkTemplate, f.Project, f.Zone, f.resourceType, f.Name)
}
// Parses a zonal field supporting 5 different formats:
// - https://www.googleapis.com/compute/ANY_VERSION/projects/{my_project}/zones/{zone}/{resource_type}/{resource_name}
// - projects/{my_project}/zones/{zone}/{resource_type}/{resource_name}
// - zones/{zone}/{resource_type}/{resource_name}
// - resource_name
// - "" (empty string). RelativeLink() returns empty if isEmptyValid is true.
//
// If the project is not specified, it first tries to get the project from the `projectSchemaField` and then fallback on the default project.
// If the zone is not specified, it takes the value of `zoneSchemaField`.
func parseZonalFieldValue(resourceType, fieldValue, projectSchemaField, zoneSchemaField string, d TerraformResourceData, config *Config, isEmptyValid bool) (*ZonalFieldValue, error) {
if len(fieldValue) == 0 {
if isEmptyValid {
return &ZonalFieldValue{resourceType: resourceType}, nil
}
return nil, fmt.Errorf("The zonal field for resource %s cannot be empty.", resourceType)
}
r := regexp.MustCompile(fmt.Sprintf(zonalLinkBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &ZonalFieldValue{
Project: parts[1],
Zone: parts[2],
Name: parts[3],
resourceType: resourceType,
}, nil
}
project, err := getProjectFromSchema(projectSchemaField, d, config)
if err != nil {
return nil, err
}
r = regexp.MustCompile(fmt.Sprintf(zonalPartialLinkBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &ZonalFieldValue{
Project: project,
Zone: parts[1],
Name: parts[2],
resourceType: resourceType,
}, nil
}
if len(zoneSchemaField) == 0 {
return nil, fmt.Errorf("Invalid field format. Got '%s', expected format '%s'", fieldValue, fmt.Sprintf(globalLinkTemplate, "{project}", resourceType, "{name}"))
}
zone, ok := d.GetOk(zoneSchemaField)
if !ok {
zone = config.Zone
if zone == "" {
return nil, fmt.Errorf("A zone must be specified")
}
}
return &ZonalFieldValue{
Project: project,
Zone: zone.(string),
Name: GetResourceNameFromSelfLink(fieldValue),
resourceType: resourceType,
}, nil
}
func getProjectFromSchema(projectSchemaField string, d TerraformResourceData, config *Config) (string, error) {
res, ok := d.GetOk(projectSchemaField)
if ok && projectSchemaField != "" {
return res.(string), nil
}
if config.Project != "" {
return config.Project, nil
}
return "", fmt.Errorf("%s: required field is not set", projectSchemaField)
}
func getBillingProjectFromSchema(billingProjectSchemaField string, d TerraformResourceData, config *Config) (string, error) {
res, ok := d.GetOk(billingProjectSchemaField)
if ok && billingProjectSchemaField != "" {
return res.(string), nil
}
if config.BillingProject != "" {
return config.BillingProject, nil
}
return "", fmt.Errorf("%s: required field is not set", billingProjectSchemaField)
}
type OrganizationFieldValue struct {
OrgId string
Name string
resourceType string
}
func (f OrganizationFieldValue) RelativeLink() string {
if len(f.Name) == 0 {
return ""
}
return fmt.Sprintf(organizationLinkTemplate, f.OrgId, f.resourceType, f.Name)
}
// Parses an organization field with the following formats:
// - organizations/{my_organizations}/{resource_type}/{resource_name}
func parseOrganizationFieldValue(resourceType, fieldValue string, isEmptyValid bool) (*OrganizationFieldValue, error) {
if len(fieldValue) == 0 {
if isEmptyValid {
return &OrganizationFieldValue{resourceType: resourceType}, nil
}
return nil, fmt.Errorf("The organization field for resource %s cannot be empty", resourceType)
}
r := regexp.MustCompile(fmt.Sprintf(organizationBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &OrganizationFieldValue{
OrgId: parts[1],
Name: parts[2],
resourceType: resourceType,
}, nil
}
return nil, fmt.Errorf("Invalid field format. Got '%s', expected format '%s'", fieldValue, fmt.Sprintf(organizationLinkTemplate, "{org_id}", resourceType, "{name}"))
}
type RegionalFieldValue struct {
Project string
Region string
Name string
resourceType string
}
func (f RegionalFieldValue) RelativeLink() string {
if len(f.Name) == 0 {
return ""
}
return fmt.Sprintf(regionalLinkTemplate, f.Project, f.Region, f.resourceType, f.Name)
}
// Parses a regional field supporting 5 different formats:
// - https://www.googleapis.com/compute/ANY_VERSION/projects/{my_project}/regions/{region}/{resource_type}/{resource_name}
// - projects/{my_project}/regions/{region}/{resource_type}/{resource_name}
// - regions/{region}/{resource_type}/{resource_name}
// - resource_name
// - "" (empty string). RelativeLink() returns empty if isEmptyValid is true.
//
// If the project is not specified, it first tries to get the project from the `projectSchemaField` and then fallback on the default project.
// If the region is not specified, see function documentation for `getRegionFromSchema`.
func parseRegionalFieldValue(resourceType, fieldValue, projectSchemaField, regionSchemaField, zoneSchemaField string, d TerraformResourceData, config *Config, isEmptyValid bool) (*RegionalFieldValue, error) {
if len(fieldValue) == 0 {
if isEmptyValid {
return &RegionalFieldValue{resourceType: resourceType}, nil
}
return nil, fmt.Errorf("The regional field for resource %s cannot be empty.", resourceType)
}
r := regexp.MustCompile(fmt.Sprintf(regionalLinkBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &RegionalFieldValue{
Project: parts[1],
Region: parts[2],
Name: parts[3],
resourceType: resourceType,
}, nil
}
project, err := getProjectFromSchema(projectSchemaField, d, config)
if err != nil {
return nil, err
}
r = regexp.MustCompile(fmt.Sprintf(regionalPartialLinkBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &RegionalFieldValue{
Project: project,
Region: parts[1],
Name: parts[2],
resourceType: resourceType,
}, nil
}
region, err := getRegionFromSchema(regionSchemaField, zoneSchemaField, d, config)
if err != nil {
return nil, err
}
return &RegionalFieldValue{
Project: project,
Region: region,
Name: GetResourceNameFromSelfLink(fieldValue),
resourceType: resourceType,
}, nil
}
// Infers the region based on the following (in order of priority):
// - `regionSchemaField` in resource schema
// - region extracted from the `zoneSchemaField` in resource schema
// - provider-level region
// - region extracted from the provider-level zone
func getRegionFromSchema(regionSchemaField, zoneSchemaField string, d TerraformResourceData, config *Config) (string, error) {
// if identical such as GKE location, check if it's a zone first and find
// the region if so. Otherwise, return as it's a region.
if regionSchemaField == zoneSchemaField {
if v, ok := d.GetOk(regionSchemaField); ok {
if isZone(v.(string)) {
return getRegionFromZone(v.(string)), nil
}
return v.(string), nil
}
}
if v, ok := d.GetOk(regionSchemaField); ok && regionSchemaField != "" {
return GetResourceNameFromSelfLink(v.(string)), nil
}
if v, ok := d.GetOk(zoneSchemaField); ok && zoneSchemaField != "" {
return getRegionFromZone(v.(string)), nil
}
if config.Region != "" {
return config.Region, nil
}
if config.Zone != "" {
return getRegionFromZone(config.Zone), nil
}
return "", fmt.Errorf("Cannot determine region: set in this resource, or set provider-level 'region' or 'zone'.")
}
type ProjectFieldValue struct {
Project string
Name string
resourceType string
}
func (f ProjectFieldValue) RelativeLink() string {
if len(f.Name) == 0 {
return ""
}
return fmt.Sprintf(projectLinkTemplate, f.Project, f.resourceType, f.Name)
}
// Parses a project field with the following formats:
// - projects/{my_projects}/{resource_type}/{resource_name}
func parseProjectFieldValue(resourceType, fieldValue, projectSchemaField string, d TerraformResourceData, config *Config, isEmptyValid bool) (*ProjectFieldValue, error) {
if len(fieldValue) == 0 {
if isEmptyValid {
return &ProjectFieldValue{resourceType: resourceType}, nil
}
return nil, fmt.Errorf("The project field for resource %s cannot be empty", resourceType)
}
r := regexp.MustCompile(fmt.Sprintf(projectBasePattern, resourceType))
if parts := r.FindStringSubmatch(fieldValue); parts != nil {
return &ProjectFieldValue{
Project: parts[1],
Name: parts[2],
resourceType: resourceType,
}, nil
}
project, err := getProjectFromSchema(projectSchemaField, d, config)
if err != nil {
return nil, err
}
return &ProjectFieldValue{
Project: project,
Name: GetResourceNameFromSelfLink(fieldValue),
resourceType: resourceType,
}, nil
}