/
command.go
73 lines (60 loc) · 1.52 KB
/
command.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
package cmd
import (
"context"
"fmt"
"os"
"github.com/dirien/devpod-provider-equinix/pkg/equinix"
"github.com/loft-sh/devpod/pkg/ssh"
"github.com/loft-sh/log"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
// CommandCmd holds the cmd flags
type CommandCmd struct{}
// NewCommandCmd defines a command
func NewCommandCmd() *cobra.Command {
cmd := &CommandCmd{}
commandCmd := &cobra.Command{
Use: "command",
Short: "Command an instance",
RunE: func(_ *cobra.Command, args []string) error {
equinixProvider, err := equinix.NewProvider(log.Default, false)
if err != nil {
return err
}
return cmd.Run(
context.Background(),
equinixProvider,
log.Default,
)
},
}
return commandCmd
}
// Run runs the command logic
func (cmd *CommandCmd) Run(
ctx context.Context,
equinixProvider *equinix.EquinixProvider,
logs log.Logger,
) error {
command := os.Getenv("COMMAND")
if command == "" {
return fmt.Errorf("command environment variable is missing")
}
privateKey, err := ssh.GetPrivateKeyRawBase(equinixProvider.Config.MachineFolder)
if err != nil {
return fmt.Errorf("load private key: %w", err)
}
// get instance
instance, _, err := equinix.GetDevpodInstance(ctx, equinixProvider)
if err != nil {
return err
}
sshClient, err := ssh.NewSSHClient("devpod", equinix.GetIP4(instance)+":22", privateKey)
if err != nil {
return errors.Wrap(err, "create ssh client")
}
defer sshClient.Close()
// run command
return ssh.Run(ctx, sshClient, command, os.Stdin, os.Stdout, os.Stderr)
}