-
Notifications
You must be signed in to change notification settings - Fork 30
/
env.go
119 lines (102 loc) · 2.39 KB
/
env.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
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
package main
import (
"encoding/json"
"os"
"sort"
"strings"
"text/template"
"github.com/miquella/vaulted/lib"
)
type Env struct {
SessionOptions
DetectedShell string
Format string
Command string
Interactive bool
}
type templateVals struct {
Command string
Interactive bool
AWSCreds struct {
ID string
Secret string
Token string `json:",omitempty"`
}
Set map[string]string
Unset []string
}
var (
sessionFormatters = map[string]string{
"fish": `
{{- if .Interactive -}}
# To load these variables into your shell, execute:
# {{ .Command }} | source
{{ end -}}
{{ range $var := .Unset}}set -e {{ $var }};
{{ end -}}
{{ range $var, $value := .Set }}set -gx {{ $var }} "{{ replace $value "\"" "\\\"" }}";
{{ end -}}
`,
"sh": `
{{- if .Interactive -}}
# To load these variables into your shell, execute:
# eval "$({{ .Command }})"
{{ end -}}
{{ range $var := .Unset}}unset {{ $var }}
{{ end -}}
{{ range $var, $value := .Set }}export {{ $var }}="{{ replace $value "\"" "\\\"" }}"
{{ end -}}
`,
"json": "{{ json .Set }}\n",
}
)
var templateFuncMap = template.FuncMap{
"replace": func(val string, toReplace string, replacement string) string {
return strings.Replace(val, toReplace, replacement, -1)
},
"json": func(val interface{}) (string, error) {
json, err := json.MarshalIndent(val, "", " ")
if err != nil {
return "", err
} else {
return string(json), nil
}
},
}
func (e *Env) Run(store vaulted.Store) error {
session, err := GetSessionWithOptions(store, &e.SessionOptions)
if err != nil {
return err
}
var templateStr string
format := e.Format
if format == "shell" {
format = e.DetectedShell
if _, ok := sessionFormatters[format]; !ok {
format = "sh"
}
}
if foundTemplate, ok := sessionFormatters[format]; ok {
templateStr = foundTemplate
} else {
templateStr = format
}
tmpl, err := template.New("sessionTmpl").Funcs(templateFuncMap).Parse(templateStr)
variables := session.Variables()
sort.Strings(variables.Unset)
vals := templateVals{
Command: e.Command,
Interactive: e.Interactive,
Set: variables.Set,
Unset: variables.Unset,
}
if session.AWSCreds != nil {
vals.AWSCreds.ID = session.AWSCreds.ID
vals.AWSCreds.Secret = session.AWSCreds.Secret
vals.AWSCreds.Token = session.AWSCreds.Token
}
if err != nil {
return ErrorWithExitCode{err, 64}
}
return tmpl.Execute(os.Stdout, vals)
}