diff --git a/completion.go b/completion.go index 117e1441..8309de09 100644 --- a/completion.go +++ b/completion.go @@ -79,7 +79,7 @@ const ( hcloud_server_reset | hcloud_server_reset-password | \ hcloud_server_shutdown | hcloud_server_disable-rescue | \ hcloud_server_enable-rescue | hcloud_server_detach-iso | \ - hcloud_server_update ) + hcloud_server_update | hcloud_server_rebuild ) __hcloud_server_names return ;; diff --git a/server.go b/server.go index d6afd48c..153c40c7 100644 --- a/server.go +++ b/server.go @@ -29,6 +29,7 @@ func newServerCommand(cli *CLI) *cobra.Command { newServerDetachISOCommand(cli), newServerUpdateCommand(cli), newServerChangeTypeCommand(cli), + newServerRebuildCommand(cli), ) return cmd } diff --git a/server_rebuild.go b/server_rebuild.go new file mode 100644 index 00000000..b7de40c4 --- /dev/null +++ b/server_rebuild.go @@ -0,0 +1,61 @@ +package cli + +import ( + "fmt" + + "github.com/hetznercloud/hcloud-go/hcloud" + "github.com/spf13/cobra" +) + +func newServerRebuildCommand(cli *CLI) *cobra.Command { + cmd := &cobra.Command{ + Use: "rebuild [FLAGS] SERVER", + Short: "Rebuild a server", + Args: cobra.ExactArgs(1), + TraverseChildren: true, + DisableFlagsInUseLine: true, + RunE: cli.wrap(runServerRebuild), + } + + cmd.Flags().String("image", "", "ID or name of image to rebuild from") + cmd.Flag("image").Annotations = map[string][]string{ + cobra.BashCompCustom: {"__hcloud_image_names"}, + } + cmd.MarkFlagRequired("image") + + return cmd +} + +func runServerRebuild(cli *CLI, cmd *cobra.Command, args []string) error { + serverIDOrName := args[0] + server, _, err := cli.Client().Server.Get(cli.Context, serverIDOrName) + if err != nil { + return err + } + if server == nil { + return fmt.Errorf("server not found: %s", serverIDOrName) + } + + imageIDOrName, _ := cmd.Flags().GetString("image") + image, _, err := cli.Client().Image.Get(cli.Context, imageIDOrName) + if err != nil { + return err + } + if image == nil { + return fmt.Errorf("image not found: %s", imageIDOrName) + } + + opts := hcloud.ServerRebuildOpts{ + Image: image, + } + action, _, err := cli.Client().Server.Rebuild(cli.Context, server, opts) + if err != nil { + return err + } + errCh, _ := waitAction(cli.Context, cli.Client(), action) + if err := <-errCh; err != nil { + return err + } + fmt.Printf("Server %s rebuilt with image %s\n", serverIDOrName, imageIDOrName) + return nil +}