From b07faab7786fa0b9ac700f56def0a80280f59653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=C3=ABl=20Cluseau?= Date: Sun, 8 Jul 2018 16:48:22 +1100 Subject: [PATCH] feat: allow to filter applied files --- cmd/dkl-apply-config/main.go | 5 ++++- pkg/apply/files.go | 29 ++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/cmd/dkl-apply-config/main.go b/cmd/dkl-apply-config/main.go index 71916a7..7770364 100644 --- a/cmd/dkl-apply-config/main.go +++ b/cmd/dkl-apply-config/main.go @@ -3,6 +3,7 @@ package main import ( "flag" "os" + "strings" "novit.nc/direktil/inits/pkg/apply" "novit.nc/direktil/pkg/config" @@ -16,6 +17,7 @@ var ( func main() { configPath := flag.String("config", "config.yaml", "config to load (\"-\" for stdin)") doFiles := flag.Bool("files", false, "apply files") + filesFilters := flag.String("files-filters", "*", "comma-separated filters to select files to apply") flag.Parse() log.SetConsole(os.Stderr) @@ -39,7 +41,8 @@ func main() { } if *doFiles { - if err = apply.Files(cfg, log); err != nil { + filters := strings.Split(*filesFilters, ",") + if err = apply.Files(cfg, log, filters...); err != nil { log.Taint(dlog.Fatal, "failed to apply files: ", err) os.Exit(1) } diff --git a/pkg/apply/files.go b/pkg/apply/files.go index 63e6e11..5f8e100 100644 --- a/pkg/apply/files.go +++ b/pkg/apply/files.go @@ -12,11 +12,30 @@ import ( dlog "novit.nc/direktil/pkg/log" ) +const ( + authorizedKeysPath = "/root/.ssh/authorized_keys" +) + // Files writes the files from the given config -func Files(cfg *config.Config, log *dlog.Log) (err error) { - if cfg.RootUser.AuthorizedKeys != nil { +func Files(cfg *config.Config, log *dlog.Log, filters ...string) (err error) { + accept := func(n string) bool { return true } + + if len(filters) > 0 { + accept = func(n string) bool { + for _, filter := range filters { + if matched, err := filepath.Match(filter, n); err != nil { + log.Taintf(dlog.Error, "bad filter ignored: %q: %v", filter, err) + } else if matched { + return true + } + } + return false + } + } + + if cfg.RootUser.AuthorizedKeys != nil && accept(authorizedKeysPath) { err = writeFile( - "/root/.ssh/authorized_keys", + authorizedKeysPath, []byte(strings.Join(cfg.RootUser.AuthorizedKeys, "\n")), 0600, 0700, cfg, log, ) @@ -27,6 +46,10 @@ func Files(cfg *config.Config, log *dlog.Log) (err error) { } for _, file := range cfg.Files { + if !accept(file.Path) { + continue + } + mode := file.Mode if mode == 0 { mode = 0644