-
Notifications
You must be signed in to change notification settings - Fork 9
/
export.go
89 lines (78 loc) · 2.23 KB
/
export.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
package openshift
import (
"bytes"
"fmt"
"regexp"
"strings"
"github.com/ghodss/yaml"
"github.com/opendevstack/tailor/pkg/cli"
)
var (
trimAnnotationsDefault = []string{
"kubectl.kubernetes.io/last-applied-configuration",
"openshift.io/image.dockerRepositoryCheck",
}
)
// ExportAsTemplateFile exports resources in template format.
func ExportAsTemplateFile(filter *ResourceFilter, withAnnotations bool, namespace string, withHardcodedNamespace bool, trimAnnotations []string, ocClient cli.OcClientExporter) (string, error) {
outBytes, err := ocClient.Export(filter.ConvertToKinds(), filter.Label)
if err != nil {
return "", fmt.Errorf("Could not export %s resources: %s", filter.String(), err)
}
if len(outBytes) == 0 {
return "", nil
}
if !withHardcodedNamespace {
namespaceRegex := regexp.MustCompile(`\b` + namespace + `\b.?`)
outBytes = namespaceRegex.ReplaceAllFunc(outBytes, func(b []byte) []byte {
if bytes.HasSuffix(b, []byte("-")) {
return b
}
return bytes.Replace(b, []byte(namespace), []byte("${TAILOR_NAMESPACE}"), -1)
})
}
list, err := NewPlatformBasedResourceList(filter, outBytes)
if err != nil {
return "", fmt.Errorf("Could not create resource list from export: %s", err)
}
objects := []map[string]interface{}{}
for _, i := range list.Items {
if withAnnotations {
cli.DebugMsg("All annotations will be kept in template item")
} else {
trimAnnotations = append(trimAnnotations, trimAnnotationsDefault...)
cli.DebugMsg("Trim annotations from template item")
for ia := range i.Annotations {
for _, ta := range trimAnnotations {
if strings.HasSuffix(ta, "/") && strings.HasPrefix(ia, ta) {
i.removeAnnotion(ia)
} else if ta == ia {
i.removeAnnotion(ia)
}
}
}
}
objects = append(objects, i.Config)
}
t := map[string]interface{}{
"apiVersion": "template.openshift.io/v1",
"kind": "Template",
"objects": objects,
}
if !withHardcodedNamespace {
parameters := []map[string]interface{}{
{
"name": "TAILOR_NAMESPACE",
"required": true,
},
}
t["parameters"] = parameters
}
b, err := yaml.Marshal(t)
if err != nil {
return "", fmt.Errorf(
"Could not marshal template: %s", err,
)
}
return string(b), err
}