github.com/opendevstack/tailor@v1.3.5-0.20220119161809-cab064e60a67/pkg/openshift/export.go (about) 1 package openshift 2 3 import ( 4 "bytes" 5 "fmt" 6 "regexp" 7 "strings" 8 9 "github.com/ghodss/yaml" 10 "github.com/opendevstack/tailor/pkg/cli" 11 ) 12 13 var ( 14 trimAnnotationsDefault = []string{ 15 "kubectl.kubernetes.io/last-applied-configuration", 16 "openshift.io/image.dockerRepositoryCheck", 17 } 18 ) 19 20 // ExportAsTemplateFile exports resources in template format. 21 func ExportAsTemplateFile(filter *ResourceFilter, withAnnotations bool, namespace string, withHardcodedNamespace bool, trimAnnotations []string, ocClient cli.OcClientExporter) (string, error) { 22 outBytes, err := ocClient.Export(filter.ConvertToKinds(), filter.Label) 23 if err != nil { 24 return "", fmt.Errorf("Could not export %s resources: %s", filter.String(), err) 25 } 26 if len(outBytes) == 0 { 27 return "", nil 28 } 29 30 if !withHardcodedNamespace { 31 namespaceRegex := regexp.MustCompile(`\b` + namespace + `\b.?`) 32 outBytes = namespaceRegex.ReplaceAllFunc(outBytes, func(b []byte) []byte { 33 if bytes.HasSuffix(b, []byte("-")) { 34 return b 35 } 36 return bytes.Replace(b, []byte(namespace), []byte("${TAILOR_NAMESPACE}"), -1) 37 }) 38 } 39 40 list, err := NewPlatformBasedResourceList(filter, outBytes) 41 if err != nil { 42 return "", fmt.Errorf("Could not create resource list from export: %s", err) 43 } 44 45 objects := []map[string]interface{}{} 46 for _, i := range list.Items { 47 if withAnnotations { 48 cli.DebugMsg("All annotations will be kept in template item") 49 } else { 50 trimAnnotations = append(trimAnnotations, trimAnnotationsDefault...) 51 cli.DebugMsg("Trim annotations from template item") 52 for ia := range i.Annotations { 53 for _, ta := range trimAnnotations { 54 if strings.HasSuffix(ta, "/") && strings.HasPrefix(ia, ta) { 55 i.removeAnnotion(ia) 56 } else if ta == ia { 57 i.removeAnnotion(ia) 58 } 59 } 60 } 61 } 62 objects = append(objects, i.Config) 63 } 64 65 t := map[string]interface{}{ 66 "apiVersion": "template.openshift.io/v1", 67 "kind": "Template", 68 "objects": objects, 69 } 70 71 if !withHardcodedNamespace { 72 parameters := []map[string]interface{}{ 73 { 74 "name": "TAILOR_NAMESPACE", 75 "required": true, 76 }, 77 } 78 t["parameters"] = parameters 79 } 80 81 b, err := yaml.Marshal(t) 82 if err != nil { 83 return "", fmt.Errorf( 84 "Could not marshal template: %s", err, 85 ) 86 } 87 88 return string(b), err 89 }