diff --git a/cloudinit/cloud_config.go b/cloudinit/cloud_config.go index e39dd32..3901990 100644 --- a/cloudinit/cloud_config.go +++ b/cloudinit/cloud_config.go @@ -17,6 +17,7 @@ type CloudConfig struct { Units []Unit } Write_Files []WriteFile + Hostname string } func NewCloudConfig(contents []byte) (*CloudConfig, error) { @@ -38,6 +39,13 @@ func (cc CloudConfig) String() string { } func ApplyCloudConfig(cfg CloudConfig, sshKeyName string) error { + if cfg.Hostname != "" { + if err := SetHostname(cfg.Hostname); err != nil { + return err + } + log.Printf("Set hostname to %s", cfg.Hostname) + } + if len(cfg.SSH_Authorized_Keys) > 0 { err := AuthorizeSSHKeys(sshKeyName, cfg.SSH_Authorized_Keys) if err == nil { diff --git a/cloudinit/cloud_config_test.go b/cloudinit/cloud_config_test.go index 827d009..3d2cfb6 100644 --- a/cloudinit/cloud_config_test.go +++ b/cloudinit/cloud_config_test.go @@ -28,6 +28,10 @@ func TestCloudConfigEmpty(t *testing.T) { if len(cfg.Write_Files) != 0 { t.Error("Expected zero Write_Files") } + + if cfg.Hostname != "" { + t.Errorf("Expected hostname to be empty, got '%s'", cfg.Hostname) + } } // Assert that the parsing of a cloud config file "generally works" @@ -61,6 +65,7 @@ write_files: path: /etc/dogepack.conf permissions: '0644' owner: root:dogepack +hostname: trontastic `) cfg, err := NewCloudConfig(contents) if err != nil { @@ -129,6 +134,9 @@ Address=10.209.171.177/19 } } + if cfg.Hostname != "trontastic" { + t.Errorf("Failed to parse hostname") + } } // Assert that our interface conversion doesn't panic diff --git a/cloudinit/systemd.go b/cloudinit/systemd.go index 5b7ad62..ee8de40 100644 --- a/cloudinit/systemd.go +++ b/cloudinit/systemd.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "log" "os" + "os/exec" "path" "path/filepath" "strings" @@ -150,3 +151,7 @@ func ExecuteScript(scriptPath string) (string, error) { _, err = conn.StartTransientUnit(name, "replace", props...) return name, err } + +func SetHostname(hostname string) error { + return exec.Command("hostnamectl", "set-hostname", hostname).Run() +}