-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate-gen
executable file
·161 lines (138 loc) · 5.94 KB
/
template-gen
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
#!/usr/bin/env python3
import argparse
import os
import re
import shlex
import subprocess
import sys
import yaml
from pathlib import Path
def main() -> None:
"""
Main function.
"""
argparser = argparse.ArgumentParser("Generate the k8s file from the template")
argparser.add_argument("--update", help="Don't run dependency update", action="store_true")
argparser.add_argument("--kube-version", help="The kubernetes version", default="1.25.0")
argparser.add_argument("--helm", help="The used helm command", default=os.environ.get("HELM", "helm"))
argparser.add_argument("--debug", help="Enable verbose output", action="store_true")
argparser.add_argument("--index", help="The release index present in the helmfile", default=0, type=int)
argparser.add_argument("--namespace", help="The namespace", default="default")
argparser.add_argument("--dry-run", help="Run the command in dry-run mode", action="store_true")
argparser.add_argument("--values", help="get the merged values", action="store_true")
argparser.add_argument("--output", help="put the result in the given file")
argparser.add_argument(
"--no-sops", help="Do not use sops to decide the secret files", action="store_true"
)
argparser.add_argument("helmfile", help="The helmfile or Chart file")
args = argparser.parse_args()
helmfile = Path(args.helmfile)
base_dir = helmfile.parent
if helmfile.name == "Chart.yaml":
chart_dir = base_dir
chart = "."
values_path = base_dir / "values.yaml"
values_filenames = ["values.yaml"] if values_path.exists() else []
release_name = base_dir.name
else:
with open(args.helmfile, encoding="utf-8") as sops_config_file:
helmfile = yaml.safe_load(sops_config_file)
release = helmfile["releases"][args.index]
chart_dir = base_dir / release["chart"]
chart = release["chart"]
values_filenames = release.get("values", [])
release_name = release["name"]
del release
helm_command = [args.helm, "template", release_name, chart]
if args.update:
subprocess.run([args.helm, "dependency", "update"], check=True, cwd=chart_dir, stdout=sys.stderr)
if args.debug:
helm_command.append("--debug")
success = True
for value in values_filenames:
value_path = base_dir / value
if not value_path.exists():
success = False
print(f"File {value_path} not found")
if not success:
sys.exit(1)
values = []
to_rm = []
no_sops = args.no_sops
sops_path = Path(__file__).parent.parent / ".sops.yaml"
if sops_path.exists():
sops_config = yaml.safe_load( sops_path.read_text(encoding="utf-8") )
secret_file_re = re.compile(sops_config["creation_rules"][0]["path_regex"])
no_sops = True
try:
if args.values:
from deepmerge import Merger
merger = Merger(
[
(list, ["override"]),
(dict, ["merge"]),
(set, ["override"]),
],
["override"],
["override"],
)
all_values = {}
for values_file in values_filenames:
if not no_sops and secret_file_re.match(values_file):
decrypted_file = base_dir / (values_file + ".decrypted")
to_rm.append(decrypted_file)
process = subprocess.run(
["sops", "--decrypt", str(base_dir / values_file)],
stdout=subprocess.PIPE,
encoding="utf-8",
)
next_values = yaml.safe_load(process.stdout)
else:
values_file = base_dir / values_file
with values_file.open(encoding="utf-8") as f:
next_values = yaml.safe_load(values_file.read())
merger.merge(all_values, next_values)
print(yaml.safe_dump(all_values))
exit(0)
for values_file in values_filenames:
if not no_sops and secret_file_re.match(values_file):
decrypted_file = base_dir / values_file + ".decrypted"
to_rm.append(str(decrypted_file) + ".decrypted")
with open(decrypted_file.with_suffix(decrypted_file.suffix + ".decrypted"), "w", encoding="utf-8") as sops_file:
subprocess.run(
["sops", "--decrypt", str(decrypted_file)],
stdout=sops_file,
)
values.append(values_file + ".decrypted")
else:
values.append(values_file)
cmd = [
*helm_command,
f"--kube-version={args.kube_version}",
f"--namespace={args.namespace}",
*[f"--values={values}" for values in values],
]
if args.dry_run:
print(shlex.join(["cd", base_dir]))
print(shlex.join(cmd))
else:
if args.output:
with open(args.output, "w", encoding="utf-8") as output_file:
proc = subprocess.run(cmd, cwd=base_dir, stdout=output_file, stderr=subprocess.DEVNULL)
else:
proc = subprocess.run(cmd, cwd=base_dir, stderr=subprocess.DEVNULL)
if proc.returncode != 0:
chart_dir = base_dir / chart
subprocess.run([args.helm, "dependency", "update"], cwd=chart_dir)
if args.output:
with open(args.output, "w", encoding="utf-8") as output_file:
proc = subprocess.run(cmd, cwd=base_dir, stdout=output_file)
else:
proc = subprocess.run(cmd, cwd=base_dir)
sys.exit(proc.returncode)
finally:
for file_ in to_rm:
if Path(file_).exists():
os.remove(file_)
if __name__ == "__main__":
main()