/
utils.go
825 lines (717 loc) · 22.5 KB
/
utils.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tpgresource
import (
"context"
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"log"
"net/url"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-cty/cty"
fwDiags "github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"google.golang.org/api/googleapi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type TerraformResourceDataChange interface {
GetChange(string) (interface{}, interface{})
}
type TerraformResourceData interface {
HasChange(string) bool
GetOkExists(string) (interface{}, bool)
GetOk(string) (interface{}, bool)
Get(string) interface{}
Set(string, interface{}) error
SetId(string)
Id() string
GetProviderMeta(interface{}) error
Timeout(key string) time.Duration
}
type TerraformResourceDiff interface {
HasChange(string) bool
GetChange(string) (interface{}, interface{})
Get(string) interface{}
GetOk(string) (interface{}, bool)
Clear(string) error
ForceNew(string) error
}
// Contains functions that don't really belong anywhere else.
// GetRegionFromZone returns the region from a zone for Google cloud.
// This is by removing the last two chars from the zone name to leave the region
// If there aren't enough characters in the input string, an empty string is returned
// e.g. southamerica-west1-a => southamerica-west1
func GetRegionFromZone(zone string) string {
if zone != "" && len(zone) > 2 {
region := zone[:len(zone)-2]
return region
}
return ""
}
// Infers the region based on the following (in order of priority):
// - `region` field in resource schema
// - region extracted from the `zone` field in resource schema
// - provider-level region
// - region extracted from the provider-level zone
func GetRegion(d TerraformResourceData, config *transport_tpg.Config) (string, error) {
return GetRegionFromSchema("region", "zone", d, config)
}
// GetProject reads the "project" field from the given resource data and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func GetProject(d TerraformResourceData, config *transport_tpg.Config) (string, error) {
return GetProjectFromSchema("project", d, config)
}
// GetUniverse reads the "universe_domain" field from the given resource data and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func GetUniverseDomain(d TerraformResourceData, config *transport_tpg.Config) (string, error) {
return GetUniverseDomainFromSchema("universe_domain", d, config)
}
// GetBillingProject reads the "billing_project" field from the given resource data and falls
// back to the provider's value if not given. If no value is found, an error is returned.
func GetBillingProject(d TerraformResourceData, config *transport_tpg.Config) (string, error) {
return GetBillingProjectFromSchema("billing_project", d, config)
}
// GetProjectFromDiff reads the "project" field from the given diff and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func GetProjectFromDiff(d *schema.ResourceDiff, config *transport_tpg.Config) (string, error) {
res, ok := d.GetOk("project")
if ok {
return res.(string), nil
}
if d.GetRawConfig().GetAttr("project") == cty.UnknownVal(cty.String) {
return res.(string), nil
}
if config.Project != "" {
return config.Project, nil
}
return "", fmt.Errorf("%s: required field is not set", "project")
}
// getRegionFromDiff reads the "region" field from the given diff and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func GetRegionFromDiff(d *schema.ResourceDiff, config *transport_tpg.Config) (string, error) {
res, ok := d.GetOk("region")
if ok {
return res.(string), nil
}
if d.GetRawConfig().GetAttr("region") == cty.UnknownVal(cty.String) {
return res.(string), nil
}
if config.Region != "" {
return config.Region, nil
}
return "", fmt.Errorf("%s: required field is not set", "region")
}
// getZoneFromDiff reads the "zone" field from the given diff and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func GetZoneFromDiff(d *schema.ResourceDiff, config *transport_tpg.Config) (string, error) {
res, ok := d.GetOk("zone")
if ok {
return res.(string), nil
}
if d.GetRawConfig().GetAttr("zone") == cty.UnknownVal(cty.String) {
return res.(string), nil
}
if config.Zone != "" {
return config.Zone, nil
}
return "", fmt.Errorf("%s: required field is not set", "zone")
}
func GetRouterLockName(region string, router string) string {
return fmt.Sprintf("router/%s/%s", region, router)
}
func IsFailedPreconditionError(err error) bool {
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if !ok {
return false
}
if gerr == nil {
return false
}
if gerr.Code != 400 {
return false
}
for _, e := range gerr.Errors {
if e.Reason == "failedPrecondition" {
return true
}
}
return false
}
func IsQuotaError(err error) bool {
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if !ok {
return false
}
if gerr == nil {
return false
}
if gerr.Code != 429 {
return false
}
return true
}
func IsConflictError(err error) bool {
if e, ok := err.(*googleapi.Error); ok && (e.Code == 409 || e.Code == 412) {
return true
} else if !ok && errwrap.ContainsType(err, &googleapi.Error{}) {
e := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if e.Code == 409 || e.Code == 412 {
return true
}
}
return false
}
// gRPC does not return errors of type *googleapi.Error. Instead the errors returned are *status.Error.
// See the types of codes returned here (https://pkg.go.dev/google.golang.org/grpc/codes#Code).
func IsNotFoundGrpcError(err error) bool {
if errorStatus, ok := status.FromError(err); ok && errorStatus.Code() == codes.NotFound {
return true
}
return false
}
// ExpandLabels pulls the value of "labels" out of a TerraformResourceData as a map[string]string.
func ExpandLabels(d TerraformResourceData) map[string]string {
return ExpandStringMap(d, "labels")
}
// ExpandEffectiveLabels pulls the value of "effective_labels" out of a TerraformResourceData as a map[string]string.
func ExpandEffectiveLabels(d TerraformResourceData) map[string]string {
return ExpandStringMap(d, "effective_labels")
}
// ExpandEnvironmentVariables pulls the value of "environment_variables" out of a schema.ResourceData as a map[string]string.
func ExpandEnvironmentVariables(d *schema.ResourceData) map[string]string {
return ExpandStringMap(d, "environment_variables")
}
// ExpandBuildEnvironmentVariables pulls the value of "build_environment_variables" out of a schema.ResourceData as a map[string]string.
func ExpandBuildEnvironmentVariables(d *schema.ResourceData) map[string]string {
return ExpandStringMap(d, "build_environment_variables")
}
// ExpandStringMap pulls the value of key out of a TerraformResourceData as a map[string]string.
func ExpandStringMap(d TerraformResourceData, key string) map[string]string {
v, ok := d.GetOk(key)
if !ok {
return map[string]string{}
}
return ConvertStringMap(v.(map[string]interface{}))
}
func ConvertStringMap(v map[string]interface{}) map[string]string {
m := make(map[string]string)
for k, val := range v {
m[k] = val.(string)
}
return m
}
func ConvertStringArr(ifaceArr []interface{}) []string {
return ConvertAndMapStringArr(ifaceArr, func(s string) string { return s })
}
func ConvertAndMapStringArr(ifaceArr []interface{}, f func(string) string) []string {
var arr []string
for _, v := range ifaceArr {
if v == nil {
continue
}
arr = append(arr, f(v.(string)))
}
return arr
}
func MapStringArr(original []string, f func(string) string) []string {
var arr []string
for _, v := range original {
arr = append(arr, f(v))
}
return arr
}
func ConvertStringArrToInterface(strs []string) []interface{} {
arr := make([]interface{}, len(strs))
for i, str := range strs {
arr[i] = str
}
return arr
}
func ConvertStringSet(set *schema.Set) []string {
s := make([]string, 0, set.Len())
for _, v := range set.List() {
s = append(s, v.(string))
}
sort.Strings(s)
return s
}
func GolangSetFromStringSlice(strings []string) map[string]struct{} {
set := map[string]struct{}{}
for _, v := range strings {
set[v] = struct{}{}
}
return set
}
func StringSliceFromGolangSet(sset map[string]struct{}) []string {
ls := make([]string, 0, len(sset))
for s := range sset {
ls = append(ls, s)
}
sort.Strings(ls)
return ls
}
func ReverseStringMap(m map[string]string) map[string]string {
o := map[string]string{}
for k, v := range m {
o[v] = k
}
return o
}
func MergeStringMaps(a, b map[string]string) map[string]string {
merged := make(map[string]string)
for k, v := range a {
merged[k] = v
}
for k, v := range b {
merged[k] = v
}
return merged
}
func MergeSchemas(a, b map[string]*schema.Schema) map[string]*schema.Schema {
merged := make(map[string]*schema.Schema)
for k, v := range a {
merged[k] = v
}
for k, v := range b {
merged[k] = v
}
return merged
}
func StringToFixed64(v string) (int64, error) {
return strconv.ParseInt(v, 10, 64)
}
func ExtractFirstMapConfig(m []interface{}) map[string]interface{} {
if len(m) == 0 || m[0] == nil {
return map[string]interface{}{}
}
return m[0].(map[string]interface{})
}
// ServiceAccountFQN will attempt to generate the fully qualified name in the format of:
//
// "projects/(-|<project>)/serviceAccounts/<service_account_id>@<project>.iam.gserviceaccount.com"
// A project is required if we are trying to build the FQN from a service account id and
// and error will be returned in this case if no project is set in the resource or the
// provider-level config
func ServiceAccountFQN(serviceAccount string, d TerraformResourceData, config *transport_tpg.Config) (string, error) {
// If the service account id is already the fully qualified name
if strings.HasPrefix(serviceAccount, "projects/") {
return serviceAccount, nil
}
// If the service account id is an email
if strings.Contains(serviceAccount, "@") {
return "projects/-/serviceAccounts/" + serviceAccount, nil
}
// Get the project from the resource or fallback to the project
// in the provider configuration
project, err := GetProject(d, config)
if err != nil {
return "", err
}
return fmt.Sprintf("projects/-/serviceAccounts/%s@%s.iam.gserviceaccount.com", serviceAccount, project), nil
}
func PaginatedListRequest(project, baseUrl, userAgent string, config *transport_tpg.Config, flattener func(map[string]interface{}) []interface{}) ([]interface{}, error) {
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: project,
RawURL: baseUrl,
UserAgent: userAgent,
})
if err != nil {
return nil, err
}
ls := flattener(res)
pageToken, ok := res["pageToken"]
for ok {
if pageToken.(string) == "" {
break
}
url := fmt.Sprintf("%s?pageToken=%s", baseUrl, pageToken.(string))
res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: project,
RawURL: url,
UserAgent: userAgent,
})
if err != nil {
return nil, err
}
ls = append(ls, flattener(res))
pageToken, ok = res["pageToken"]
}
return ls, nil
}
func GetInterconnectAttachmentLink(config *transport_tpg.Config, project, region, ic, userAgent string) (string, error) {
if !strings.Contains(ic, "/") {
icData, err := config.NewComputeClient(userAgent).InterconnectAttachments.Get(
project, region, ic).Do()
if err != nil {
return "", fmt.Errorf("Error reading interconnect attachment: %s", err)
}
ic = icData.SelfLink
}
return ic, nil
}
// Given two sets of references (with "from" values in self link form),
// determine which need to be added or removed // during an update using
// addX/removeX APIs.
func CalcAddRemove(from []string, to []string) (add, remove []string) {
add = make([]string, 0)
remove = make([]string, 0)
for _, u := range to {
found := false
for _, v := range from {
if CompareSelfLinkOrResourceName("", v, u, nil) {
found = true
break
}
}
if !found {
add = append(add, u)
}
}
for _, u := range from {
found := false
for _, v := range to {
if CompareSelfLinkOrResourceName("", u, v, nil) {
found = true
break
}
}
if !found {
remove = append(remove, u)
}
}
return add, remove
}
func StringInSlice(arr []string, str string) bool {
for _, i := range arr {
if i == str {
return true
}
}
return false
}
func MigrateStateNoop(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
return is, nil
}
func ExpandString(v interface{}, d TerraformResourceData, config *transport_tpg.Config) (string, error) {
return v.(string), nil
}
func ChangeFieldSchemaToForceNew(sch *schema.Schema) {
sch.ForceNew = true
switch sch.Type {
case schema.TypeList:
case schema.TypeSet:
if nestedR, ok := sch.Elem.(*schema.Resource); ok {
for _, nestedSch := range nestedR.Schema {
ChangeFieldSchemaToForceNew(nestedSch)
}
}
}
}
func GenerateUserAgentString(d TerraformResourceData, currentUserAgent string) (string, error) {
var m transport_tpg.ProviderMeta
err := d.GetProviderMeta(&m)
if err != nil {
return currentUserAgent, err
}
if m.ModuleName != "" {
return strings.Join([]string{currentUserAgent, m.ModuleName}, " "), nil
}
return currentUserAgent, nil
}
func SnakeToPascalCase(s string) string {
split := strings.Split(s, "_")
for i := range split {
split[i] = strings.Title(split[i])
}
return strings.Join(split, "")
}
func CheckStringMap(v interface{}) map[string]string {
m, ok := v.(map[string]string)
if ok {
return m
}
return ConvertStringMap(v.(map[string]interface{}))
}
// return a fake 404 so requests get retried or nested objects are considered deleted
func Fake404(reasonResourceType, resourceName string) *googleapi.Error {
return &googleapi.Error{
Code: 404,
Message: fmt.Sprintf("%v object %v not found", reasonResourceType, resourceName),
}
}
// validate name of the gcs bucket. Guidelines are located at https://cloud.google.com/storage/docs/naming-buckets
// this does not attempt to check for IP addresses or close misspellings of "google"
func CheckGCSName(name string) error {
if strings.HasPrefix(name, "goog") {
return fmt.Errorf("error: bucket name %s cannot start with %q", name, "goog")
}
if strings.Contains(name, "google") {
return fmt.Errorf("error: bucket name %s cannot contain %q", name, "google")
}
valid, _ := regexp.MatchString("^[a-z0-9][a-z0-9_.-]{1,220}[a-z0-9]$", name)
if !valid {
return fmt.Errorf("error: bucket name validation failed %v. See https://cloud.google.com/storage/docs/naming-buckets", name)
}
for _, str := range strings.Split(name, ".") {
valid, _ := regexp.MatchString("^[a-z0-9_-]{1,63}$", str)
if !valid {
return fmt.Errorf("error: bucket name validation failed %v", str)
}
}
return nil
}
// CheckGoogleIamPolicy makes assertions about the contents of a google_iam_policy data source's policy_data attribute
func CheckGoogleIamPolicy(value string) error {
if strings.Contains(value, "\"description\":\"\"") {
return fmt.Errorf("found an empty description field (should be omitted) in google_iam_policy data source: %s", value)
}
return nil
}
func FrameworkDiagsToSdkDiags(fwD fwDiags.Diagnostics) *diag.Diagnostics {
var diags diag.Diagnostics
for _, e := range fwD.Errors() {
diags = append(diags, diag.Diagnostic{
Detail: e.Detail(),
Severity: diag.Error,
Summary: e.Summary(),
})
}
for _, w := range fwD.Warnings() {
diags = append(diags, diag.Diagnostic{
Detail: w.Detail(),
Severity: diag.Warning,
Summary: w.Summary(),
})
}
return &diags
}
func IsEmptyValue(v reflect.Value) bool {
if !v.IsValid() {
return true
}
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
return false
}
func ReplaceVars(d TerraformResourceData, config *transport_tpg.Config, linkTmpl string) (string, error) {
return ReplaceVarsRecursive(d, config, linkTmpl, false, 0)
}
// relaceVarsForId shortens variables by running them through GetResourceNameFromSelfLink
// this allows us to use long forms of variables from configs without needing
// custom id formats. For instance:
// accessPolicies/{{access_policy}}/accessLevels/{{access_level}}
// with values:
// access_policy: accessPolicies/foo
// access_level: accessPolicies/foo/accessLevels/bar
// becomes accessPolicies/foo/accessLevels/bar
func ReplaceVarsForId(d TerraformResourceData, config *transport_tpg.Config, linkTmpl string) (string, error) {
return ReplaceVarsRecursive(d, config, linkTmpl, true, 0)
}
// ReplaceVars must be done recursively because there are baseUrls that can contain references to regions
// (eg cloudrun service) there aren't any cases known for 2+ recursion but we will track a run away
// substitution as 10+ calls to allow for future use cases.
func ReplaceVarsRecursive(d TerraformResourceData, config *transport_tpg.Config, linkTmpl string, shorten bool, depth int) (string, error) {
if depth > 10 {
return "", errors.New("Recursive substitution detected")
}
// https://github.com/google/re2/wiki/Syntax
re := regexp.MustCompile("{{([%[:word:]]+)}}")
f, err := BuildReplacementFunc(re, d, config, linkTmpl, shorten)
if err != nil {
return "", err
}
final := re.ReplaceAllStringFunc(linkTmpl, f)
if re.Match([]byte(final)) {
return ReplaceVarsRecursive(d, config, final, shorten, depth+1)
}
return final, nil
}
// This function replaces references to Terraform properties (in the form of {{var}}) with their value in Terraform
// It also replaces {{project}}, {{project_id_or_project}}, {{region}}, and {{zone}} with their appropriate values
// This function supports URL-encoding the result by prepending '%' to the field name e.g. {{%var}}
func BuildReplacementFunc(re *regexp.Regexp, d TerraformResourceData, config *transport_tpg.Config, linkTmpl string, shorten bool) (func(string) string, error) {
var project, projectID, region, zone string
var err error
if strings.Contains(linkTmpl, "{{project}}") {
project, err = GetProject(d, config)
if err != nil {
return nil, err
}
if shorten {
project = strings.TrimPrefix(project, "projects/")
}
}
if strings.Contains(linkTmpl, "{{project_id_or_project}}") {
v, ok := d.GetOkExists("project_id")
if ok {
projectID, _ = v.(string)
}
if projectID == "" {
project, err = GetProject(d, config)
}
if err != nil {
return nil, err
}
if shorten {
project = strings.TrimPrefix(project, "projects/")
projectID = strings.TrimPrefix(projectID, "projects/")
}
}
if strings.Contains(linkTmpl, "{{region}}") {
region, err = GetRegion(d, config)
if err != nil {
return nil, err
}
if shorten {
region = strings.TrimPrefix(region, "regions/")
}
}
if strings.Contains(linkTmpl, "{{zone}}") {
zone, err = GetZone(d, config)
if err != nil {
return nil, err
}
if shorten {
zone = strings.TrimPrefix(zone, "zones/")
}
}
f := func(s string) string {
m := re.FindStringSubmatch(s)[1]
if m == "project" {
return project
}
if m == "project_id_or_project" {
if projectID != "" {
return projectID
}
return project
}
if m == "region" {
return region
}
if m == "zone" {
return zone
}
if string(m[0]) == "%" {
v, ok := d.GetOkExists(m[1:])
if ok {
return url.PathEscape(fmt.Sprintf("%v", v))
}
} else {
v, ok := d.GetOkExists(m)
if ok {
if shorten {
return GetResourceNameFromSelfLink(fmt.Sprintf("%v", v))
} else {
return fmt.Sprintf("%v", v)
}
}
}
// terraform-google-conversion doesn't provide a provider config in tests.
if config != nil {
// Attempt to draw values from the provider config if it's present.
if f := reflect.Indirect(reflect.ValueOf(config)).FieldByName(m); f.IsValid() {
return f.String()
}
}
return ""
}
return f, nil
}
func GetFileMd5Hash(filename string) string {
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("[WARN] Failed to read source file %q. Cannot compute md5 hash for it.", filename)
return ""
}
return GetContentMd5Hash(data)
}
func GetContentMd5Hash(content []byte) string {
h := md5.New()
if _, err := h.Write(content); err != nil {
log.Printf("[WARN] Failed to compute md5 hash for content: %v", err)
}
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func DefaultProviderProject(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
config := meta.(*transport_tpg.Config)
//project
if project := diff.Get("project"); project != nil {
project2, err := GetProjectFromDiff(diff, config)
if err != nil {
return fmt.Errorf("Failed to retrieve project, pid: %s, err: %s", project, err)
}
if CompareSelfLinkRelativePaths("", project.(string), project2, nil) {
return nil
}
err = diff.SetNew("project", project2)
if err != nil {
return err
}
}
return nil
}
func DefaultProviderRegion(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
config := meta.(*transport_tpg.Config)
//region
if region := diff.Get("region"); region != nil {
region, err := GetRegionFromDiff(diff, config)
if err != nil {
return fmt.Errorf("Failed to retrieve region, pid: %s, err: %s", region, err)
}
err = diff.SetNew("region", region)
if err != nil {
return err
}
}
return nil
}
func DefaultProviderZone(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
config := meta.(*transport_tpg.Config)
// zone
if zone := diff.Get("zone"); zone != nil {
zone, err := GetZoneFromDiff(diff, config)
if err != nil {
return fmt.Errorf("Failed to retrieve zone, pid: %s, err: %s", zone, err)
}
err = diff.SetNew("zone", zone)
if err != nil {
return err
}
}
return nil
}