forked from stackitcloud/stackit-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackit_cli_flow.go
More file actions
78 lines (68 loc) · 1.89 KB
/
stackit_cli_flow.go
File metadata and controls
78 lines (68 loc) · 1.89 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
package clients
import (
"bytes"
"context"
"errors"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
)
// STACKITCLIFlow invoke the STACKIT CLI from PATH to get the access token.
// If successful, then token is passed to clients.TokenFlow.
type STACKITCLIFlow struct {
TokenFlow
}
// STACKITCLIFlowConfig is the flow config
type STACKITCLIFlowConfig struct {
HTTPTransport http.RoundTripper
}
// GetConfig returns the flow configuration
func (c *STACKITCLIFlow) GetConfig() STACKITCLIFlowConfig {
return STACKITCLIFlowConfig{}
}
func (c *STACKITCLIFlow) Init(cfg *STACKITCLIFlowConfig) error {
token, err := c.getTokenFromCLI()
if err != nil {
return err
}
return c.TokenFlow.Init(&TokenFlowConfig{
ServiceAccountToken: strings.TrimSpace(token),
HTTPTransport: cfg.HTTPTransport,
})
}
func (c *STACKITCLIFlow) getTokenFromCLI() (string, error) {
return RunSTACKITCLICommand(context.TODO(), "stackit auth get-access-token")
}
// RunSTACKITCLICommand executes the command line and returns the output.
func RunSTACKITCLICommand(ctx context.Context, commandLine string) (string, error) {
var cliCmd *exec.Cmd
if runtime.GOOS == "windows" {
dir := os.Getenv("SYSTEMROOT")
if dir == "" {
return "", errors.New("environment variable 'SYSTEMROOT' has no value")
}
cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine)
cliCmd.Dir = dir
} else {
cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine)
cliCmd.Dir = "/bin"
}
cliCmd.Env = os.Environ()
var stderr bytes.Buffer
cliCmd.Stderr = &stderr
output, err := cliCmd.Output()
if err != nil {
msg := stderr.String()
var exErr *exec.ExitError
if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'stackit' is not recognized") {
msg = "STACKIT CLI not found on path"
}
if msg == "" {
msg = err.Error()
}
return "", errors.New(msg)
}
return string(output), nil
}