Skip to content

Commit f0cf480

Browse files
committed
Extract hostname from (hostname.domainname)
This approach allows the user to provide a FQDN as hostname if that is what they want in their container, or to provide distinct host and domain parts. In both cases we will correctly extract the first token for /etc/hosts. Signed-off-by: Tim Hockin <thockin@google.com>
1 parent 9994ce1 commit f0cf480

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

etchosts/etchosts.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"io/ioutil"
99
"os"
1010
"regexp"
11+
"strings"
1112
"sync"
1213
)
1314

@@ -78,10 +79,17 @@ func Build(path, IP, hostname, domainname string, extraContent []Record) error {
7879
//set main record
7980
var mainRec Record
8081
mainRec.IP = IP
82+
// User might have provided a FQDN in hostname or split it across hostname
83+
// and domainname. We want the FQDN and the bare hostname.
84+
fqdn := hostname
8185
if domainname != "" {
82-
mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname)
86+
fqdn = fmt.Sprintf("%s.%s", fqdn, domainname)
87+
}
88+
parts := strings.SplitN(fqdn, ".", 2)
89+
if len(parts) == 2 {
90+
mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0])
8391
} else {
84-
mainRec.Hosts = hostname
92+
mainRec.Hosts = fqdn
8593
}
8694
if _, err := mainRec.WriteTo(content); err != nil {
8795
return err

etchosts/etchosts_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,28 @@ func TestBuildHostname(t *testing.T) {
8181
}
8282
}
8383

84+
func TestBuildHostnameFQDN(t *testing.T) {
85+
file, err := ioutil.TempFile("", "")
86+
if err != nil {
87+
t.Fatal(err)
88+
}
89+
defer os.Remove(file.Name())
90+
91+
err = Build(file.Name(), "10.11.12.13", "testhostname.testdomainname.com", "", nil)
92+
if err != nil {
93+
t.Fatal(err)
94+
}
95+
96+
content, err := ioutil.ReadFile(file.Name())
97+
if err != nil {
98+
t.Fatal(err)
99+
}
100+
101+
if expected := "10.11.12.13\ttesthostname.testdomainname.com testhostname\n"; !bytes.Contains(content, []byte(expected)) {
102+
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
103+
}
104+
}
105+
84106
func TestBuildNoIP(t *testing.T) {
85107
file, err := ioutil.TempFile("", "")
86108
if err != nil {

0 commit comments

Comments
 (0)