diff --git a/docs/Templates.md b/docs/Templates.md index 35f10a05..cca780b5 100644 --- a/docs/Templates.md +++ b/docs/Templates.md @@ -4,6 +4,8 @@ In additional to the [built-in Go template functions and features][tt], `webhook` provides a `getenv` template function for inserting environment variables into a templated configuration file. +`secret` template function provides access to docker secrets. `secret secret_name` will insert content of `/run/secrets/secret_name` file into a templated configuration file. + ## Example Usage In the example JSON template file below (YAML is also supported), the `payload-hmac-sha1` matching rule looks up the HMAC secret from the environment using the `getenv` template function. diff --git a/internal/hook/hook.go b/internal/hook/hook.go index 05100957..eba4c056 100644 --- a/internal/hook/hook.go +++ b/internal/hook/hook.go @@ -19,8 +19,10 @@ import ( "net" "net/textproto" "os" + "path/filepath" "reflect" "regexp" + "runtime" "strconv" "strings" "text/template" @@ -757,8 +759,10 @@ func (h *Hooks) LoadFromFile(path string, asTemplate bool) error { } if asTemplate { - funcMap := template.FuncMap{"getenv": getenv} - + funcMap := template.FuncMap{ + "getenv": getenv, + "secret": dockerSecret, + } tmpl, err := template.New("hooks").Funcs(funcMap).Parse(string(file)) if err != nil { return err @@ -956,3 +960,19 @@ func compare(a, b string) bool { func getenv(s string) string { return os.Getenv(s) } + +// dockerSecret provides a template function to retrieve Docker secret. +func dockerSecret(name string) string { + _, file := filepath.Split(name) + if runtime.GOOS == "windows" { + file = filepath.Join("C:\\ProgramData\\Docker\\secrets", file) + } else { + file = filepath.Join("/run/secrets", file) + } + b, err := ioutil.ReadFile(file) + if err != nil { + log.Printf("error reading docker secret from %s %s", file, err) + return "" + } + return string(b) +}