-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathattachPolicy.go
More file actions
87 lines (74 loc) · 2.11 KB
/
attachPolicy.go
File metadata and controls
87 lines (74 loc) · 2.11 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"fmt"
"io"
"net/http"
"github.com/kosli-dev/cli/internal/requests"
"github.com/spf13/cobra"
)
type AttachPolicyPayload struct {
PolicyNames []string `json:"policy_names"`
}
type attachPolicyOptions struct {
payload AttachPolicyPayload
environments []string
}
const attachPolicyShortDesc = `Attach a policy to one or more Kosli environments. `
const attachPolicyExample = `
# attach previously created policy to multiple environment:
kosli attach-policy yourPolicyName \
--environment yourFirstEnvironmentName \
--environment yourSecondEnvironmentName \
--api-token yourAPIToken \
--org yourOrgName
`
func newAttachPolicyCmd(out io.Writer) *cobra.Command {
o := new(attachPolicyOptions)
cmd := &cobra.Command{
Use: "attach-policy POLICY-NAME",
Short: attachPolicyShortDesc,
Long: attachPolicyShortDesc,
Example: attachPolicyExample,
Hidden: true,
Args: cobra.ExactArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
err := RequireGlobalFlags(global, []string{"Org", "ApiToken"})
if err != nil {
return ErrorBeforePrintingUsage(cmd, err.Error())
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return o.run(args)
},
}
cmd.Flags().StringSliceVarP(&o.environments, "environment", "e", []string{}, attachPolicyEnvFlag)
addDryRunFlag(cmd)
err := RequireFlags(cmd, []string{"environment"})
if err != nil {
logger.Error("failed to configure required flags: %v", err)
}
return cmd
}
func (o *attachPolicyOptions) run(args []string) error {
var err error
for _, env := range o.environments {
url := fmt.Sprintf("%s/api/v2/environments/%s/%s/policies", global.Host, global.Org, env)
o.payload.PolicyNames = []string{args[0]}
reqParams := &requests.RequestParams{
Method: http.MethodPost,
URL: url,
Payload: o.payload,
DryRun: global.DryRun,
Password: global.ApiToken,
}
_, err = kosliClient.Do(reqParams)
if err != nil {
break
}
}
if err == nil && global.DryRun == "false" {
logger.Info("policy '%s' is attached to environments: %s", args[0], o.environments)
}
return err
}