forked from gen0cide/laforge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_builder.go
75 lines (67 loc) · 1.87 KB
/
template_builder.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
package competition
import (
"bytes"
"errors"
"fmt"
"html/template"
"path/filepath"
"reflect"
"strings"
)
type TemplateBuilder struct {
Competition *Competition
Environment *Environment
PodID int
Network *Network
Host *Host
HostIndex int
}
func (t *TemplateBuilder) EnvItemName(i interface{}, opts ...string) string {
optString := ""
if len(opts) > 0 {
optString = fmt.Sprintf("_%s", strings.Join(opts, "_"))
}
name := strings.ToLower(reflect.TypeOf(i).Name())
return fmt.Sprintf("%s_%s%s", t.Environment.Suffix(t.PodID), name, optString)
}
func (t *TemplateBuilder) NetItemName(i interface{}, opts ...string) string {
optString := ""
if len(opts) > 0 {
optString = fmt.Sprintf("_%s", strings.Join(opts, "_"))
}
name := strings.ToLower(reflect.TypeOf(i).Name())
return fmt.Sprintf("%s_%s_%s%s", t.Environment.Suffix(t.PodID), t.Network.Name, name, optString)
}
type TFTemplate struct {
Name string
Builder TemplateBuilder
Template string
Rendered string
}
func NewTemplateContext(c *Competition, e *Environment, pid int, n *Network, h *Host) *TemplateBuilder {
return &TemplateBuilder{
Competition: c,
Environment: e,
PodID: pid,
Network: n,
Host: h,
}
}
func TFRender(tfobj interface{}) (string, error) {
tmplName := strings.ToLower(reflect.TypeOf(tfobj).Name())
filename := tmplName + ".tmpl"
tmplFile := filepath.Join("terraform", filename)
asset, err := Asset(tmplFile)
if err != nil {
return "", err
}
var tmplBuffer bytes.Buffer
tmpl, err := template.New(tmplName).Parse(string(asset))
if err != nil {
return "", errors.New("Fatal Error parsing terraform template (" + tmplFile + "): " + err.Error())
}
if err := tmpl.Execute(&tmplBuffer, tfobj); err != nil {
return "", errors.New("Fatal Error rendering terraform template (" + tmplFile + "): " + err.Error())
}
return tmplBuffer.String(), nil
}