forked from Shopify/ejson2env
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secrets.go
54 lines (42 loc) · 1.46 KB
/
secrets.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
package ejson2env
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"github.com/Shopify/ejson"
)
// ExportFunction is implemented in exportSecrets as an easy way
// to select how secrets are exported
type ExportFunction func(io.Writer, map[string]string)
// output is a pointer to the io.Writer to use. This allows us to override
// stdout for testing purposes.
var output io.Writer = os.Stdout
// readSecrets reads the secrets for the passed filename and
// returns them as a map[string]interface{}.
func readSecrets(filename, keyDir, privateKey string) (map[string]interface{}, error) {
secrets := make(map[string]interface{})
decrypted, err := ejson.DecryptFile(filename, keyDir, privateKey)
if nil != err {
return secrets, err
}
decoder := json.NewDecoder(bytes.NewReader(decrypted))
err = decoder.Decode(&secrets)
return secrets, err
}
// IsEnvError returns true if the passed error is due to the environment
// being missing or not containing environment variables.
func IsEnvError(err error) bool {
return (errNoEnv == err || errEnvNotMap == err)
}
// ReadAndExportEnv wraps the read, extract, and export steps. Returns
// an error if any step fails.
func ReadAndExportEnv(filename, keyDir, privateKey string, exportFunc ExportFunction) error {
envValues, err := ReadAndExtractEnv(filename, keyDir, privateKey)
if nil != err && !IsEnvError(err) {
return fmt.Errorf("could not load environment from file: %s", err)
}
exportFunc(output, envValues)
return nil
}