hostname.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package hostname
  2. import (
  3. "bufio"
  4. "io/ioutil"
  5. "os"
  6. "strings"
  7. "syscall"
  8. "github.com/rancher/os/config"
  9. )
  10. func SetHostnameFromCloudConfig(cc *config.CloudConfig) error {
  11. var hostname string
  12. if cc.Hostname == "" {
  13. hostname = cc.Rancher.Defaults.Hostname
  14. } else {
  15. hostname = cc.Hostname
  16. }
  17. if hostname == "" {
  18. return nil
  19. }
  20. // set hostname
  21. if err := syscall.Sethostname([]byte(hostname)); err != nil {
  22. return err
  23. }
  24. return nil
  25. }
  26. func SyncHostname() error {
  27. hostname, err := os.Hostname()
  28. if err != nil {
  29. return err
  30. }
  31. if hostname == "" {
  32. return nil
  33. }
  34. hosts, err := os.Open("/etc/hosts")
  35. defer hosts.Close()
  36. if err != nil {
  37. return err
  38. }
  39. lines := bufio.NewScanner(hosts)
  40. hostsContent := ""
  41. for lines.Scan() {
  42. line := strings.TrimSpace(lines.Text())
  43. fields := strings.Fields(line)
  44. if len(fields) > 0 && fields[0] == "127.0.1.1" {
  45. hostsContent += "127.0.1.1 " + hostname + "\n"
  46. continue
  47. }
  48. hostsContent += line + "\n"
  49. }
  50. if err := ioutil.WriteFile("/etc/hosts", []byte(hostsContent), 0600); err != nil {
  51. return err
  52. }
  53. return nil
  54. }