-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathcreate_image.go
More file actions
70 lines (57 loc) · 1.93 KB
/
create_image.go
File metadata and controls
70 lines (57 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package server
import (
"fmt"
"github.com/spf13/cobra"
"github.com/hetznercloud/cli/internal/cmd/base"
"github.com/hetznercloud/cli/internal/cmd/cmpl"
"github.com/hetznercloud/cli/internal/hcapi2"
"github.com/hetznercloud/cli/internal/state"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)
var CreateImageCmd = base.Cmd{
BaseCobraCommand: func(hcapi2.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "create-image [options] --type <snapshot|backup> <server>",
Short: "Create an Image from a Server",
}
cmd.Flags().String("type", "", "Image type (backup, snapshot) (required)")
_ = cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("backup", "snapshot"))
_ = cmd.MarkFlagRequired("type")
cmd.Flags().String("description", "", "Image description")
cmd.Flags().StringToString("label", nil, "User-defined labels ('key=value') (can be specified multiple times)")
return cmd
},
Run: func(s state.State, cmd *cobra.Command, args []string) error {
idOrName := args[0]
server, _, err := s.Client().Server().Get(s, idOrName)
if err != nil {
return err
}
if server == nil {
return fmt.Errorf("Server not found: %s", idOrName)
}
imageType, _ := cmd.Flags().GetString("type")
description, _ := cmd.Flags().GetString("description")
labels, _ := cmd.Flags().GetStringToString("label")
switch hcloud.ImageType(imageType) {
case hcloud.ImageTypeBackup, hcloud.ImageTypeSnapshot:
break
default:
return fmt.Errorf("invalid Image type: %v", imageType)
}
opts := &hcloud.ServerCreateImageOpts{
Type: hcloud.ImageType(imageType),
Description: hcloud.Ptr(description),
Labels: labels,
}
result, _, err := s.Client().Server().CreateImage(s, server, opts)
if err != nil {
return err
}
if err := s.WaitForActions(s, cmd, result.Action); err != nil {
return err
}
cmd.Printf("Image %d created from Server %d\n", result.Image.ID, server.ID)
return nil
},
}