1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package sampleconversion
16
17 import (
18 "fmt"
19 "regexp"
20 "strings"
21
22 "k8s.io/apimachinery/pkg/runtime/schema"
23 )
24
25
26
27
28
29 func GetTFReferenceValue(value interface{}) (tfRefValue, valueTemplate string, containsTFReference bool, err error) {
30 str, ok := value.(string)
31 if !ok {
32 return "", "", false, nil
33 }
34 tfRefValueRegex := regexp.MustCompile(`\${(google_[a-z_]+[a-z]\.[a-z](?:[a-z_-]*[a-z])*\.[a-z](?:[a-z_]*[a-z])*)}`)
35 matchResult := tfRefValueRegex.FindStringSubmatch(str)
36 if len(matchResult) == 0 {
37 return "", "", false, nil
38 }
39
40
41 if matchResult[0] == str {
42 return matchResult[1], "", true, nil
43 }
44
45 if len(matchResult) > 2 {
46 return "", "", false, fmt.Errorf("cannot handle more than one TF references: %v", str)
47 }
48
49 valueTemplate = strings.ReplaceAll(str, matchResult[0], "{{value}}")
50 return matchResult[1], valueTemplate, true, nil
51 }
52
53 func ConstructKRMNameReferenceObject(value string, tfToGVK map[string]schema.GroupVersionKind) (map[string]interface{}, error) {
54 tfType := strings.Split(value, ".")[0]
55 gvk, ok := tfToGVK[tfType]
56 if !ok {
57 return nil, fmt.Errorf("unsupported reference TF type: %v", tfType)
58 }
59 nameVal := fmt.Sprintf("%s-${uniqueId}", strings.ToLower(gvk.Kind))
60 refVal := make(map[string]interface{})
61 refVal["name"] = nameVal
62 return refVal, nil
63 }
64
65 func ConstructKRMExternalReferenceObject(value string) map[string]interface{} {
66 refVal := make(map[string]interface{})
67 refVal["external"] = value
68 return refVal
69 }
70
71
72
73
74
75 func ConstructKRMExternalRefValFromTFRefVal(tfRefVal, valueTemplate string, tfToGVK map[string]schema.GroupVersionKind) (string, error) {
76 tfType, field := extractReferencedTFTypeAndField(tfRefVal)
77
78 if field != "name" {
79 return "", fmt.Errorf("unsupported referenced field: %v", field)
80 }
81 gvk, ok := tfToGVK[tfType]
82 if !ok {
83 return "", fmt.Errorf("unsupported reference type: %v", tfType)
84 }
85 nameVal := fmt.Sprintf("%s-${uniqueId}", strings.ToLower(gvk.Kind))
86 return strings.ReplaceAll(valueTemplate, "{{value}}", nameVal), nil
87 }
88
89 func extractReferencedTFTypeAndField(tfRefVal string) (tfType, field string) {
90 parts := strings.Split(tfRefVal, ".")
91 tfType = parts[0]
92 field = parts[2]
93 return tfType, field
94 }
95
View as plain text