Skip to content

Commit eb7e8f5

Browse files
authored
feat: Add two template functions (#712)
* chore: replace ioutil.ReadFile by os.ReadFile * feat: Add two template functions - cat: Allows reading a value from a file - credential: Allows reading a credential passed by systemd
1 parent 7bb6808 commit eb7e8f5

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

internal/hook/hook.go

+31-3
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@ import (
1313
"errors"
1414
"fmt"
1515
"hash"
16-
"io/ioutil"
1716
"log"
1817
"math"
1918
"net"
2019
"net/textproto"
2120
"os"
21+
"path"
2222
"reflect"
2323
"regexp"
2424
"strconv"
@@ -750,14 +750,18 @@ func (h *Hooks) LoadFromFile(path string, asTemplate bool) error {
750750
}
751751

752752
// parse hook file for hooks
753-
file, e := ioutil.ReadFile(path)
753+
file, e := os.ReadFile(path)
754754

755755
if e != nil {
756756
return e
757757
}
758758

759759
if asTemplate {
760-
funcMap := template.FuncMap{"getenv": getenv}
760+
funcMap := template.FuncMap{
761+
"cat": cat,
762+
"credential": credential,
763+
"getenv": getenv,
764+
}
761765

762766
tmpl, err := template.New("hooks").Funcs(funcMap).Parse(string(file))
763767
if err != nil {
@@ -956,3 +960,27 @@ func compare(a, b string) bool {
956960
func getenv(s string) string {
957961
return os.Getenv(s)
958962
}
963+
964+
// cat provides a template function to retrieve content of files
965+
// Similarly to getenv, if no file is found, it returns the empty string
966+
func cat(s string) string {
967+
data, e := os.ReadFile(s)
968+
969+
if e != nil {
970+
return ""
971+
}
972+
973+
return string(data)
974+
}
975+
976+
// credential provides a template function to retreive secrets using systemd's LoadCredential mechanism
977+
func credential(s string) string {
978+
dir := getenv("CREDENTIALS_DIRECTORY")
979+
980+
// If no credential directory is found, fallback to the env variable
981+
if dir == "" {
982+
return getenv(s)
983+
}
984+
985+
return cat(path.Join(dir, s))
986+
}

0 commit comments

Comments
 (0)