inits/pkg/apply/files.go

90 lines
1.6 KiB
Go
Raw Normal View History

2018-07-06 08:07:37 +00:00
package apply
import (
"fmt"
"io/ioutil"
2019-03-08 01:21:29 +00:00
"log"
2018-07-06 08:07:37 +00:00
"os"
"path/filepath"
"strings"
"novit.nc/direktil/inits/pkg/vars"
"novit.nc/direktil/pkg/config"
)
2018-07-08 05:48:22 +00:00
const (
authorizedKeysPath = "/root/.ssh/authorized_keys"
)
2018-07-06 08:07:37 +00:00
// Files writes the files from the given config
2019-03-08 01:21:29 +00:00
func Files(cfg *config.Config, filters ...string) (err error) {
2018-07-08 05:48:22 +00:00
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 {
2019-03-08 01:21:29 +00:00
log.Printf("ERROR: bad filter ignored: %q: %v", filter, err)
2018-07-08 05:48:22 +00:00
} else if matched {
return true
}
}
return false
}
}
if cfg.RootUser.AuthorizedKeys != nil && accept(authorizedKeysPath) {
err = writeFile(
2018-07-08 05:48:22 +00:00
authorizedKeysPath,
[]byte(strings.Join(cfg.RootUser.AuthorizedKeys, "\n")),
2019-03-08 01:21:29 +00:00
0600, 0700, cfg,
)
2018-07-06 08:07:37 +00:00
if err != nil {
return
}
2018-07-06 08:07:37 +00:00
}
for _, file := range cfg.Files {
2018-07-08 05:48:22 +00:00
if !accept(file.Path) {
continue
}
2018-07-06 08:07:37 +00:00
mode := file.Mode
if mode == 0 {
mode = 0644
}
content := []byte(file.Content)
err = writeFile(
file.Path,
content,
mode,
0755,
cfg,
)
if err != nil {
return
}
}
return
}
2019-03-08 01:21:29 +00:00
func writeFile(path string, content []byte, fileMode, dirMode os.FileMode, cfg *config.Config) (err error) {
2018-07-06 08:07:37 +00:00
if err = os.MkdirAll(filepath.Dir(path), dirMode); err != nil {
return
}
content = vars.Substitute(content, cfg)
log.Printf("writing %q, mode %04o, %d bytes", path, fileMode, len(content))
if err = ioutil.WriteFile(path, content, fileMode); err != nil {
err = fmt.Errorf("failed to write %s: %v", path, err)
}
return
}