about summary refs log tree commit diff
path: root/ops/kontemplate/main.go
blob: c98229f5cd976658e8bd5107085d5aa29ff3d4cb (plain) (blame)
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
// Copyright (C) 2016-2019  Vincent Ambo <mail@tazj.in>
//
// Kontemplate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/alecthomas/kingpin/v2"
	"github.com/tazjin/kontemplate/context"
	"github.com/tazjin/kontemplate/templater"
)

const version string = "1.8.0"

// This variable will be initialised by the Go linker during the builder
var gitHash string

var (
	app = kingpin.New("kontemplate", "simple Kubernetes resource templating")

	// Global flags
	includes   = app.Flag("include", "Resource sets to include explicitly").Short('i').Strings()
	excludes   = app.Flag("exclude", "Resource sets to exclude explicitly").Short('e').Strings()
	variables  = app.Flag("var", "Provide variables to templates explicitly").Strings()
	kubectlBin = app.Flag("kubectl", "Path to the kubectl binary (default 'kubectl')").Default("kubectl").String()

	// Commands
	template          = app.Command("template", "Template resource sets and print them")
	templateFile      = template.Arg("file", "Cluster configuration file to use").Required().String()
	templateOutputDir = template.Flag("output", "Output directory in which to save templated files instead of printing them").Short('o').String()

	apply       = app.Command("apply", "Template resources and pass to 'kubectl apply'")
	applyFile   = apply.Arg("file", "Cluster configuration file to use").Required().String()
	applyDryRun = apply.Flag("dry-run", "Print remote operations without executing them").Default("false").Bool()

	replace     = app.Command("replace", "Template resources and pass to 'kubectl replace'")
	replaceFile = replace.Arg("file", "Cluster configuration file to use").Required().String()

	delete     = app.Command("delete", "Template resources and pass to 'kubectl delete'")
	deleteFile = delete.Arg("file", "Cluster configuration file to use").Required().String()

	create     = app.Command("create", "Template resources and pass to 'kubectl create'")
	createFile = create.Arg("file", "Cluster configuration file to use").Required().String()

	versionCmd = app.Command("version", "Show kontemplate version")
)

func main() {
	app.HelpFlag.Short('h')

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case template.FullCommand():
		templateCommand()

	case apply.FullCommand():
		applyCommand()

	case replace.FullCommand():
		replaceCommand()

	case delete.FullCommand():
		deleteCommand()

	case create.FullCommand():
		createCommand()

	case versionCmd.FullCommand():
		versionCommand()
	}
}

func versionCommand() {
	if gitHash == "" {
		fmt.Printf("Kontemplate version %s (git commit unknown)\n", version)
	} else {
		fmt.Printf("Kontemplate version %s (git commit: %s)\n", version, gitHash)
	}
}

func templateCommand() {
	_, resourceSets := loadContextAndResources(templateFile)

	for _, rs := range *resourceSets {
		if len(rs.Resources) == 0 {
			fmt.Fprintf(os.Stderr, "Warning: Resource set '%s' does not exist or contains no valid templates\n", rs.Name)
			continue
		}

		if *templateOutputDir != "" {
			templateIntoDirectory(templateOutputDir, rs)
		} else {
			for _, r := range rs.Resources {
				fmt.Fprintf(os.Stderr, "Rendered file %s/%s:\n", rs.Name, r.Filename)
				fmt.Println(r.Rendered)
			}
		}
	}
}

func templateIntoDirectory(outputDir *string, rs templater.RenderedResourceSet) {
	// Attempt to create the output directory if it does not
	// already exist:
	if err := os.MkdirAll(*templateOutputDir, 0775); err != nil {
		app.Fatalf("Could not create output directory: %v\n", err)
	}

	// Nested resource sets may contain slashes in their names.
	// These are replaced with dashes for the purpose of writing a
	// flat list of output files:
	setName := strings.Replace(rs.Name, "/", "-", -1)

	for _, r := range rs.Resources {
		filename := fmt.Sprintf("%s/%s-%s", *templateOutputDir, setName, r.Filename)
		fmt.Fprintf(os.Stderr, "Writing file %s\n", filename)

		file, err := os.Create(filename)
		if err != nil {
			app.Fatalf("Could not create file %s: %v\n", filename, err)
		}

		_, err = fmt.Fprintf(file, r.Rendered)
		if err != nil {
			app.Fatalf("Error writing file %s: %v\n", filename, err)
		}
	}
}

func applyCommand() {
	ctx, resources := loadContextAndResources(applyFile)

	var kubectlArgs []string

	if *applyDryRun {
		kubectlArgs = []string{"apply", "-f", "-", "--dry-run"}
	} else {
		kubectlArgs = []string{"apply", "-f", "-"}
	}

	if err := runKubectlWithResources(ctx, &kubectlArgs, resources); err != nil {
		failWithKubectlError(err)
	}
}

func replaceCommand() {
	ctx, resources := loadContextAndResources(replaceFile)
	args := []string{"replace", "--save-config=true", "-f", "-"}

	if err := runKubectlWithResources(ctx, &args, resources); err != nil {
		failWithKubectlError(err)
	}
}

func deleteCommand() {
	ctx, resources := loadContextAndResources(deleteFile)
	args := []string{"delete", "-f", "-"}

	if err := runKubectlWithResources(ctx, &args, resources); err != nil {
		failWithKubectlError(err)
	}
}

func createCommand() {
	ctx, resources := loadContextAndResources(createFile)
	args := []string{"create", "--save-config=true", "-f", "-"}

	if err := runKubectlWithResources(ctx, &args, resources); err != nil {
		failWithKubectlError(err)
	}
}

func loadContextAndResources(file *string) (*context.Context, *[]templater.RenderedResourceSet) {
	ctx, err := context.LoadContext(*file, variables)
	if err != nil {
		app.Fatalf("Error loading context: %v\n", err)
	}

	resources, err := templater.LoadAndApplyTemplates(includes, excludes, ctx)
	if err != nil {
		app.Fatalf("Error templating resource sets: %v\n", err)
	}

	return ctx, &resources
}

func runKubectlWithResources(c *context.Context, kubectlArgs *[]string, resourceSets *[]templater.RenderedResourceSet) error {
	argsWithContext := append(*kubectlArgs, fmt.Sprintf("--context=%s", c.Name))

	for _, rs := range *resourceSets {
		if len(rs.Resources) == 0 {
			fmt.Fprintf(os.Stderr, "Warning: Resource set '%s' contains no valid templates\n", rs.Name)
			continue
		}

		argsWithResourceSetArgs := append(argsWithContext, rs.Args...)

		kubectl := exec.Command(*kubectlBin, argsWithResourceSetArgs...)

		stdin, err := kubectl.StdinPipe()
		if err != nil {
			return fmt.Errorf("kubectl error: %v", err)
		}

		kubectl.Stdout = os.Stdout
		kubectl.Stderr = os.Stderr

		if err = kubectl.Start(); err != nil {
			return fmt.Errorf("kubectl error: %v", err)
		}

		for _, r := range rs.Resources {
			fmt.Printf("Passing file %s/%s to kubectl\n", rs.Name, r.Filename)
			fmt.Fprintln(stdin, r.Rendered)
		}
		stdin.Close()

		if err = kubectl.Wait(); err != nil {
			return err
		}
	}

	return nil
}

func failWithKubectlError(err error) {
	app.Fatalf("Kubectl error: %v\n", err)
}