1
0
Fork 0
mirror of https://github.com/Luzifer/yaml-vault.git synced 2024-12-20 20:11:16 +00:00

Improve code quality

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2019-01-09 16:17:44 +01:00
parent 1540ea328d
commit 1cd015ad67
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E

101
main.go
View file

@ -4,29 +4,33 @@ import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"text/template"
"gopkg.in/yaml.v2"
"github.com/Luzifer/rconfig"
"github.com/hashicorp/vault/api"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
korvike "github.com/Luzifer/korvike/functions"
"github.com/Luzifer/rconfig"
)
var (
cfg = struct {
File string `flag:"file,f" default:"vault.yaml" description:"File to import from / export to"`
File string `flag:"file,f" default:"vault.yaml" description:"File to import from / export to" validate:"non-zero"`
Import bool `flag:"import" default:"false" description:"Enable importing data into Vault"`
Export bool `flag:"export" default:"false" description:"Enable exporting data from Vault"`
ExportPaths []string `flag:"export-paths" default:"secret" description:"Which paths to export"`
IgnoreErrors bool `flag:"ignore-errors" default:"false" description:"Do not exit on read/write errors"`
LogLevel string `flag:"log-level" default:"info" description:"Log level (debug, info, warn, error, fatal)"`
VaultAddress string `flag:"vault-addr" env:"VAULT_ADDR" default:"https://127.0.0.1:8200" description:"Vault API address"`
VaultToken string `flag:"vault-token" env:"VAULT_TOKEN" vardefault:"vault-token" description:"Specify a token to use instead of app-id auth"`
VaultToken string `flag:"vault-token" env:"VAULT_TOKEN" vardefault:"vault-token" description:"Specify a token to use instead of app-id auth" validate:"non-zero"`
VersionAndExit bool `flag:"version" default:"false" description:"Print program version and exit"`
Verbose bool `flag:"verbose,v" default:"false" description:"Print verbose output"`
Verbose bool `flag:"verbose,v" default:"false" description:"Print verbose output [DEPRECATED]"`
}{}
version = "dev"
@ -44,16 +48,6 @@ type importField struct {
type execFunction func(*api.Client) error
func debug(format string, v ...interface{}) {
if cfg.Verbose {
log.Printf(format, v...)
}
}
func info(format string, v ...interface{}) {
log.Printf(format, v...)
}
func vaultTokenFromDisk() string {
vf, err := homedir.Expand("~/.vault-token")
if err != nil {
@ -72,30 +66,35 @@ func init() {
rconfig.SetVariableDefaults(map[string]string{
"vault-token": vaultTokenFromDisk(),
})
rconfig.Parse(&cfg)
if err := rconfig.ParseAndValidate(&cfg); err != nil {
log.WithError(err).Fatal("Unable to parse commandline options")
}
if cfg.VersionAndExit {
fmt.Printf("vault2env %s\n", version)
os.Exit(0)
}
if cfg.VaultToken == "" {
log.Fatalf("[ERR] You need to set vault-token")
if l, err := log.ParseLevel(cfg.LogLevel); err != nil {
log.WithError(err).Fatal("Unable to parse log level")
} else {
log.SetLevel(l)
}
if cfg.File == "" {
log.Fatalf("[ERR] You need to specify a file")
if cfg.Verbose {
// Backwards compatibility
log.SetLevel(log.DebugLevel)
}
if cfg.Export == cfg.Import {
log.Fatalf("[ERR] You need to either import or export")
log.Fatal("You need to either import or export")
}
if _, err := os.Stat(cfg.File); (err == nil && cfg.Export) || (err != nil && cfg.Import) {
if cfg.Export {
log.Fatalf("[ERR] Output file exists, stopping now.")
log.Fatal("Output file exists, stopping now.")
}
log.Fatalf("[ERR] Input file does not exist, stopping now.")
log.Fatal("Input file does not exist, stopping now.")
}
}
@ -104,7 +103,7 @@ func main() {
Address: cfg.VaultAddress,
})
if err != nil {
log.Fatalf("Unable to create client: %s", err)
log.WithError(err).Fatal("Unable to create client")
}
client.SetToken(cfg.VaultToken)
@ -118,7 +117,7 @@ func main() {
}
if err = ex(client); err != nil {
log.Fatalf("[ERR] %s", err)
log.WithError(err).Fatal("Unable to execute requested action")
}
}
@ -135,13 +134,13 @@ func exportFromVault(client *api.Client) error {
}
if err := readRecurse(client, path, &out); err != nil {
return err
return errors.Wrap(err, "Unable to read from Vault")
}
}
data, err := yaml.Marshal(out)
if err != nil {
return err
return errors.Wrap(err, "Unable to marshal yaml")
}
return ioutil.WriteFile(cfg.File, data, 0600)
@ -151,29 +150,29 @@ func readRecurse(client *api.Client, path string, out *importFile) error {
if !strings.HasSuffix(path, "/") {
secret, err := client.Logical().Read(path)
if err != nil {
return err
return errors.Wrapf(err, "Unable to read path %q", path)
}
if secret == nil {
if cfg.IgnoreErrors {
info("Unable to read %s: %#v", path, secret)
log.WithField("path", path).Info("Unable to read nil secret")
return nil
}
return fmt.Errorf("Unable to read %s: %#v", path, secret)
return errors.Errorf("Unable to read non-existent path %s", path)
}
out.Keys = append(out.Keys, importField{Key: path, Values: secret.Data})
debug("Successfully read data from key '%s'", path)
log.WithField("path", path).Debug("Successfully read data from key")
return nil
}
secret, err := client.Logical().List(path)
if err != nil {
if cfg.IgnoreErrors {
info("Error reading %s: %s", path, err)
log.WithError(err).WithField("path", path).Error("Error reading secret")
return nil
}
return fmt.Errorf("Error reading %s: %s", path, err)
return errors.Wrapf(err, "Error reading %s", path)
}
if secret != nil && secret.Data["keys"] != nil {
@ -191,37 +190,38 @@ func readRecurse(client *api.Client, path string, out *importFile) error {
func importToVault(client *api.Client) error {
keysRaw, err := ioutil.ReadFile(cfg.File)
if err != nil {
return err
return errors.Wrap(err, "Unable to read input file")
}
keysRaw, err = parseImportFile(keysRaw)
if err != nil {
return err
return errors.Wrap(err, "Unable to parse input file")
}
var keys importFile
if err := yaml.Unmarshal(keysRaw, &keys); err != nil {
return err
return errors.Wrap(err, "Unable to unmarshal input file")
}
for _, field := range keys.Keys {
if field.State == "absent" {
if _, err := client.Logical().Delete(field.Key); err != nil {
if cfg.IgnoreErrors {
info("Error while deleting key '%s': %s", field.Key, err)
log.WithError(err).WithField("path", field.Key).Error("Error while deleting key")
continue
}
return err
return errors.Wrapf(err, "Unable to delete path %q", field.Key)
}
log.WithField("path", field.Key).Info("Successfully deleted key")
} else {
if _, err := client.Logical().Write(field.Key, field.Values); err != nil {
if cfg.IgnoreErrors {
info("Error while writing data to key '%s': %s", field.Key, err)
log.WithError(err).WithField("path", field.Key).Error("Error while writing data to key")
continue
}
return err
return errors.Wrapf(err, "Unable to write path %q", field.Key)
}
debug("Successfully wrote data to key '%s'", field.Key)
log.WithField("path", field.Key).Debug("Successfully wrote data to key")
}
}
@ -229,25 +229,12 @@ func importToVault(client *api.Client) error {
}
func parseImportFile(in []byte) (out []byte, err error) {
funcMap := template.FuncMap{
"env": func(name string, v ...string) string {
defaultValue := ""
if len(v) > 0 {
defaultValue = v[0]
}
if value, ok := os.LookupEnv(name); ok {
return value
}
return defaultValue
},
}
t, err := template.New("input file").Funcs(funcMap).Parse(string(in))
t, err := template.New("input file").Funcs(korvike.GetFunctionMap()).Parse(string(in))
if err != nil {
return nil, err
return nil, errors.Wrap(err, "Unable to parse template")
}
buf := bytes.NewBuffer([]byte{})
err = t.Execute(buf, nil)
return buf.Bytes(), err
return buf.Bytes(), errors.Wrap(err, "Unable to execute template")
}