File: create.go

package info (click to toggle)
hcloud-cli 1.39.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,628 kB
  • sloc: sh: 36; makefile: 7
file content (82 lines) | stat: -rw-r--r-- 2,212 bytes parent folder | download | duplicates (2)
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
71
72
73
74
75
76
77
78
79
80
81
82
package sshkey

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/spf13/cobra"

	"github.com/hetznercloud/cli/internal/cmd/util"
	"github.com/hetznercloud/cli/internal/state"
	"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

func newCreateCommand(cli *state.State) *cobra.Command {
	cmd := &cobra.Command{
		Use:                   "create FLAGS",
		Short:                 "Create a SSH key",
		Args:                  cobra.NoArgs,
		TraverseChildren:      true,
		DisableFlagsInUseLine: true,
		PreRunE:               util.ChainRunE(validateCreate, cli.EnsureToken),
		RunE:                  cli.Wrap(runCreate),
	}
	cmd.Flags().String("name", "", "Key name (required)")
	cmd.Flags().String("public-key", "", "Public key")
	cmd.Flags().String("public-key-from-file", "", "Path to file containing public key")
	cmd.Flags().StringToString("label", nil, "User-defined labels ('key=value') (can be specified multiple times)")
	return cmd
}

func validateCreate(cmd *cobra.Command, args []string) error {
	if name, _ := cmd.Flags().GetString("name"); name == "" {
		return errors.New("flag --name is required")
	}

	publicKey, _ := cmd.Flags().GetString("public-key")
	publicKeyFile, _ := cmd.Flags().GetString("public-key-from-file")
	if publicKey != "" && publicKeyFile != "" {
		return errors.New("flags --public-key and --public-key-from-file are mutually exclusive")
	}

	return nil
}

func runCreate(cli *state.State, cmd *cobra.Command, args []string) error {
	name, _ := cmd.Flags().GetString("name")
	publicKey, _ := cmd.Flags().GetString("public-key")
	publicKeyFile, _ := cmd.Flags().GetString("public-key-from-file")
	labels, _ := cmd.Flags().GetStringToString("label")

	if publicKeyFile != "" {
		var (
			data []byte
			err  error
		)
		if publicKeyFile == "-" {
			data, err = ioutil.ReadAll(os.Stdin)
		} else {
			data, err = ioutil.ReadFile(publicKeyFile)
		}
		if err != nil {
			return err
		}
		publicKey = string(data)
	}

	opts := hcloud.SSHKeyCreateOpts{
		Name:      name,
		PublicKey: publicKey,
		Labels:    labels,
	}
	sshKey, _, err := cli.Client().SSHKey.Create(cli.Context, opts)
	if err != nil {
		return err
	}

	fmt.Printf("SSH key %d created\n", sshKey.ID)

	return nil
}