6
6
"fmt"
7
7
"io"
8
8
"os"
9
+ "path/filepath"
9
10
"strings"
10
11
11
12
"github.com/go-logr/logr"
@@ -21,6 +22,7 @@ import (
21
22
type templateCommandFlags struct {
22
23
parameterValues []string
23
24
export bool
25
+ outputDir string
24
26
}
25
27
26
28
var flags templateCommandFlags
@@ -29,15 +31,19 @@ var CreateCommand = &cobra.Command{
29
31
Use : "template" ,
30
32
Short : "Create template resources" ,
31
33
Example : `
32
- export or apply rendered resources of template to cluster or path
33
- gitops create template.yaml --values key1=value1,key2=value2 --export > clusters/management/template.yaml
34
+ # export rendered resources of template to stdout
35
+ gitops create template.yaml --values key1=value1,key2=value2 --export
36
+
37
+ # apply rendered resources of template to path
38
+ gitops create template.yaml --values key1=value1,key2=value2 --output-dir ./out
34
39
` ,
35
40
RunE : templatesCmdRunE (),
36
41
}
37
42
38
43
func init () {
39
44
CreateCommand .Flags ().StringSliceVar (& flags .parameterValues , "values" , []string {}, "Set parameter values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)" )
40
45
CreateCommand .Flags ().BoolVar (& flags .export , "export" , false , "export in YAML format to stdout" )
46
+ CreateCommand .Flags ().StringVar (& flags .outputDir , "output-dir" , "" , "write YAML format to file" )
41
47
}
42
48
43
49
func templatesCmdRunE () func (* cobra.Command , []string ) error {
@@ -81,6 +87,11 @@ func templatesCmdRunE() func(*cobra.Command, []string) error {
81
87
}
82
88
83
89
if flags .export {
90
+ renderedTemplate := ""
91
+ for _ , file := range templateResources .RenderedTemplate {
92
+ renderedTemplate += "\n # path: " + * file .Path + "\n ---\n " + * file .Content
93
+ }
94
+
84
95
err := export (renderedTemplate , os .Stdout )
85
96
if err != nil {
86
97
return fmt .Errorf ("failed to export rendered template: %w" , err )
@@ -89,7 +100,35 @@ func templatesCmdRunE() func(*cobra.Command, []string) error {
89
100
return nil
90
101
}
91
102
92
- return nil
103
+ if flags .outputDir != "" {
104
+ for _ , res := range templateResources .RenderedTemplate {
105
+ filePath := filepath .Join (flags .outputDir , * res .Path )
106
+ directoryPath := filepath .Dir (filePath )
107
+
108
+ err := os .MkdirAll (directoryPath , 0755 )
109
+
110
+ if err != nil {
111
+ return fmt .Errorf ("failed to create directory: %w" , err )
112
+ }
113
+
114
+ file , err := os .Create (filePath )
115
+
116
+ if err != nil {
117
+ return fmt .Errorf ("failed to create file: %w" , err )
118
+ }
119
+
120
+ defer file .Close ()
121
+
122
+ _ , err = file .Write ([]byte (* res .Content ))
123
+
124
+ if err != nil {
125
+ return fmt .Errorf ("failed to write to file: %w" , err )
126
+ }
127
+ }
128
+ return nil
129
+ }
130
+
131
+ return errors .New ("Please provide either --export or --output-dir" )
93
132
}
94
133
}
95
134
0 commit comments