This repository has been archived by the owner on Jun 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
context.go
80 lines (66 loc) · 1.96 KB
/
context.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
package phases
import (
"os"
"strings"
"github.com/flosch/pongo2"
log "github.com/sirupsen/logrus"
. "github.com/flanksource/konfigadm/pkg/types"
. "github.com/flanksource/konfigadm/pkg/utils"
)
var Context Phase = context{}
type context struct{}
func (p context) ApplyPhase(sys *Config, ctx *SystemContext) ([]Command, Filesystem, error) {
var commands []Command
files := Filesystem{}
sys.Environment = ToStringMap(interpolateMap(ctx, sys.Environment))
sys.Files = ToStringMap(interpolateMap(ctx, sys.Files))
sys.Templates = ToStringMap(interpolateMap(ctx, sys.Templates))
return commands, files, nil
}
func interpolate(c *SystemContext, s string) string {
return interpolateString(s, c.Vars)
}
func interpolateSlice(c *SystemContext, val []string) []string {
var out []string
for _, v := range val {
out = append(out, interpolate(c, v))
}
return out
}
func interpolateMap(c *SystemContext, val map[string]string) map[string]interface{} {
var out = make(map[string]interface{})
for k, v := range val {
out[k] = interpolate(c, v)
}
return out
}
func ConvertSyntaxFromJinjaToPongo(template string) string {
// jinja used filter(arg), pongo uses filter:arg
template = strings.Replace(template, "(", ":", -1)
template = strings.Replace(template, ")", "", -1)
return template
}
func interpolateString(template string, vars map[string]interface{}) string {
if len(template) == 0 {
return ""
}
if strings.Contains(template, "lookup(") {
log.Tracef("ansible lookups not supported %s", template)
return template
}
if strings.HasPrefix(template, "$") && os.Getenv(template[1:]) != "" {
return os.Getenv(template[1:])
}
template = ConvertSyntaxFromJinjaToPongo(template)
tpl, err := pongo2.FromString(template)
if err != nil {
log.Tracef("error parsing template %s: %v", template, err)
return template
}
out, err := tpl.Execute(vars)
if err != nil {
log.Tracef("error executing template %s: %v", template, err)
return template
}
return out
}