Back up /etc/hosts and allow local changes

This commit is contained in:
Shannon V. Davidson
2020-12-22 23:08:35 -06:00
parent a741b7e668
commit c43fcededc
3 changed files with 55 additions and 6 deletions

View File

@@ -1,6 +1,4 @@
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
{{$.PrevHostFile}}# Do not edit after this line - these host entries are maintained by warewulf
{{range $node := $.AllNodes}}
# Entry for {{$node.Id.Get}}
@@ -12,3 +10,4 @@
{{- end}}
{{- end}}
{{end}}

View File

@@ -7,12 +7,14 @@ import (
"github.com/hpcng/warewulf/internal/pkg/wwlog"
"github.com/spf13/cobra"
"os"
"bytes"
"text/template"
)
type TemplateStruct struct {
Ipaddr string
Fqdn string
PrevHostFile string
Ipaddr string
Fqdn string
AllNodes []node.NodeInfo
}
@@ -42,7 +44,40 @@ func CobraRunE(cmd *cobra.Command, args []string) error {
os.Exit(1)
}
w, err := os.OpenFile("/etc/hosts", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
replace.PrevHostFile = ""
w, err := os.Open("/etc/hosts")
if err != nil {
wwlog.Printf(wwlog.WARN, "%s\n", err)
} else {
// if /etc/hosts.ww does not exist, backup /etc/hosts to /etc/hosts.wwbackup
if ! util.IsFile("/etc/hosts.wwbackup") {
err = util.CopyFile("/etc/hosts", "/etc/hosts.wwbackup")
if err != nil {
wwlog.Printf(wwlog.ERROR, "%s\n", err)
}
}
// read all lines before the # warewulf comment and put into PrevHostFile template variable
lines, _ := util.ReadFile("/etc/hosts")
if lines != nil {
var buffer bytes.Buffer
for _, line := range lines {
//wwlog.Printf(wwlog.INFO, "Reading line: %s\n", line)
if util.ValidString(line, "^#.*maintained by warewulf") {
break
}
buffer.WriteString(line)
buffer.WriteString("\n")
}
replace.PrevHostFile = buffer.String()
}
}
//wwlog.Printf(wwlog.INFO, "PrevHostFile is %s\n", replace.PrevHostFile)
w.Close()
w, err = os.OpenFile("/etc/hosts", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
wwlog.Printf(wwlog.ERROR, "%s\n", err)
os.Exit(1)

View File

@@ -11,6 +11,7 @@ import (
"path/filepath"
"regexp"
"time"
"bufio"
// "strings"
)
@@ -114,6 +115,20 @@ func IsFile(path string) bool {
return false
}
func ReadFile(path string) ([]string, error) {
lines := []string{}
f, err := os.Open(path)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
f.Close()
return lines, nil
}
func ValidString(pattern string, expr string) bool {
if b, _ := regexp.MatchString(expr, pattern); b == true {
return true