Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add server rebuild command #31

Merged
merged 1 commit into from
Jan 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
;;
Expand Down
1 change: 1 addition & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func newServerCommand(cli *CLI) *cobra.Command {
newServerDetachISOCommand(cli),
newServerUpdateCommand(cli),
newServerChangeTypeCommand(cli),
newServerRebuildCommand(cli),
)
return cmd
}
Expand Down
61 changes: 61 additions & 0 deletions server_rebuild.go
Original file line number Diff line number Diff line change
@@ -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
}