/
set.go
105 lines (88 loc) · 2.36 KB
/
set.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
101
102
103
104
105
package vars
import (
"strings"
"github.com/hashicorp/go-tfe"
"github.com/logandavies181/tfd/v2/cmd/config"
"github.com/logandavies181/tfd/v2/cmd/flags"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var varsSetCmd = &cobra.Command{
Use: "set",
Aliases: []string{"s"},
Short: "Create or update a variable on a workspace",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, _ []string) error {
baseConfig, err := flags.InitializeCmd(cmd)
if err != nil {
return err
}
config := varsSetConfig{
Config: baseConfig,
Category: viper.GetString("category"),
Description: viper.GetString("description"),
Hcl: viper.GetBool("hcl"),
Key: viper.GetString("key"),
NoClobber: viper.GetBool("no-clobber"),
Sensitive: viper.GetBool("sensitive"),
Value: viper.GetString("value"),
Workspace: viper.GetString("workspace"),
}
return varsSet(config)
},
}
func init() {
VarsCmd.AddCommand(varsSetCmd)
flags.AddCategoryFlag(varsSetCmd)
flags.AddDescriptionFlag(varsSetCmd)
flags.AddHclFlag(varsSetCmd)
flags.AddKeyFlag(varsSetCmd)
flags.AddNoClobberFlag(varsSetCmd)
flags.AddSensitiveFlag(varsSetCmd)
flags.AddValueFlag(varsSetCmd)
flags.AddWorkspaceFlag(varsSetCmd)
}
type varsSetConfig struct {
config.Config
Category string
Description string
Hcl bool
Key string
NoClobber bool
Sensitive bool
Value string
Workspace string
}
func varsSet(cfg varsSetConfig) error {
ws, err := cfg.Client.Workspaces.Read(cfg.Ctx, cfg.Org, cfg.Workspace)
if err != nil {
return err
}
_, err = cfg.Client.Variables.Create(cfg.Ctx, ws.ID, tfe.VariableCreateOptions{
Category: categoryType(cfg.Category),
Description: &cfg.Description,
HCL: &cfg.Hcl,
Key: &cfg.Key,
Sensitive: &cfg.Sensitive,
Value: &cfg.Value,
})
if err != nil && !strings.Contains(err.Error(), "Key has already been taken") {
return err
}
if cfg.NoClobber {
return nil
}
wsVar, err := getVarByName(cfg.Config, cfg.Workspace, cfg.Key)
if err != nil {
return err
}
_, err = cfg.Client.Variables.Update(cfg.Ctx, ws.ID, wsVar.ID, tfe.VariableUpdateOptions{
Category: categoryType(cfg.Category),
Description: &cfg.Description,
HCL: &cfg.Hcl,
Key: &cfg.Key,
Sensitive: &cfg.Sensitive,
Value: &cfg.Value,
})
return err
}