/
update_core_instance_secret.go
100 lines (81 loc) · 2.34 KB
/
update_core_instance_secret.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package coreinstance
import (
"encoding/json"
"errors"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/calyptia/api/types"
"github.com/calyptia/cli/completer"
cfg "github.com/calyptia/cli/config"
"github.com/calyptia/cli/formatters"
)
func NewCmdUpdateCoreInstanceSecret(config *cfg.Config) *cobra.Command {
loader := completer.Completer{Config: config}
var instanceKey string
var key, value string
cmd := &cobra.Command{
Use: "core_instance_secret", // update
Short: "Update core instance secret",
Long: "Update a secret within a core instance",
RunE: func(cmd *cobra.Command, args []string) error {
fs := cmd.Flags()
if !fs.Changed("value") {
cmd.Print("Enter secret value: ")
var err error
if value, err = readPassword(); err != nil {
cmd.Println()
return err
}
cmd.Println()
}
instanceID, err := loader.LoadCoreInstanceID(instanceKey, "")
if err != nil {
return err
}
ctx := cmd.Context()
secrets, err := config.Cloud.CoreInstanceSecrets(ctx, types.ListCoreInstanceSecrets{
CoreInstanceID: instanceID,
})
if err != nil {
return err
}
var secretID string
for _, s := range secrets.Items {
if s.Key == key {
secretID = s.ID
break
}
}
if secretID == "" {
return errors.New("secret not found")
}
newValue := []byte(value)
out, err := config.Cloud.UpdateCoreInstanceSecret(ctx, types.UpdateCoreInstanceSecret{
ID: secretID,
Value: &newValue,
})
if err != nil {
return err
}
outputFormat := formatters.OutputFormatFromFlags(fs)
if fn, ok := formatters.ShouldApplyTemplating(outputFormat); ok {
return fn(cmd.OutOrStdout(), formatters.TemplateFromFlags(fs), out)
}
switch outputFormat {
case formatters.OutputFormatJSON:
return json.NewEncoder(cmd.OutOrStdout()).Encode(out)
case formatters.OutputFormatYAML:
return yaml.NewEncoder(cmd.OutOrStdout()).Encode(out)
default:
return formatters.RenderUpdated(cmd.OutOrStdout(), out)
}
},
}
fs := cmd.Flags()
fs.StringVar(&instanceKey, "core-instance", "", "Parent core instance ID or name")
fs.StringVar(&key, "key", "", "Secret key")
fs.StringVar(&value, "value", "", "Secret value")
_ = cmd.RegisterFlagCompletionFunc("core-instance", loader.CompleteCoreInstances)
_ = cmd.MarkFlagRequired("key")
return cmd
}