feat: allow to filter applied files

This commit is contained in:
Mikaël Cluseau 2018-07-08 16:48:22 +11:00
parent 2ab852992f
commit b07faab778
2 changed files with 30 additions and 4 deletions

View File

@ -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)
}

View File

@ -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