Skip to content

Commit ce4bb7d

Browse files
committed
Check if ssh is available
1 parent fcd16c6 commit ce4bb7d

File tree

1 file changed

+37
-8
lines changed

1 file changed

+37
-8
lines changed

cmd/coder/config_ssh.go

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@ import (
44
"context"
55
"fmt"
66
"io/ioutil"
7+
"net"
78
"net/url"
89
"os"
910
"path/filepath"
1011
"strings"
12+
"time"
1113

1214
"cdr.dev/coder-cli/internal/config"
1315
"cdr.dev/coder-cli/internal/entclient"
@@ -32,7 +34,7 @@ func (cmd *configSSHCmd) Spec() cli.CommandSpec {
3234
return cli.CommandSpec{
3335
Name: "config-ssh",
3436
Usage: "",
35-
Desc: "adds your Coder Enterprise environments to ~/.ssh/config",
37+
Desc: "add your Coder Enterprise environments to ~/.ssh/config",
3638
}
3739
}
3840

@@ -82,6 +84,11 @@ func (cmd *configSSHCmd) Run(fl *pflag.FlagSet) {
8284

8385
entClient := requireAuth()
8486

87+
sshAvailable := cmd.ensureSSHAvailable(ctx)
88+
if !sshAvailable {
89+
flog.Fatal("SSH is disabled or not available for your Coder Enterprise deployment.")
90+
}
91+
8592
me, err := entClient.Me()
8693
if err != nil {
8794
flog.Fatal("failed to fetch username: %v", err)
@@ -129,18 +136,14 @@ func writeSSHKey(ctx context.Context, client *entclient.Client) error {
129136
}
130137

131138
func (cmd *configSSHCmd) makeNewConfigs(userName string, envs []entclient.Environment) (string, error) {
132-
u, err := config.URL.Read()
139+
hostname, err := configuredHostname()
133140
if err != nil {
134-
return "", err
135-
}
136-
url, err := url.Parse(u)
137-
if err != nil {
138-
return "", err
141+
return "", nil
139142
}
140143

141144
newConfig := fmt.Sprintf("\n%s\n%s\n\n", cmd.startToken, cmd.startMessage)
142145
for _, env := range envs {
143-
newConfig += cmd.makeConfig(url.Hostname(), userName, env.Name)
146+
newConfig += cmd.makeConfig(hostname, userName, env.Name)
144147
}
145148
newConfig += fmt.Sprintf("\n%s\n", cmd.endToken)
146149

@@ -158,6 +161,32 @@ func (cmd *configSSHCmd) makeConfig(host, userName, envName string) string {
158161
`, envName, host, userName, envName, privateKeyFilepath)
159162
}
160163

164+
func (cmd *configSSHCmd) ensureSSHAvailable(ctx context.Context) bool {
165+
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
166+
defer cancel()
167+
168+
host, err := configuredHostname()
169+
if err != nil {
170+
return false
171+
}
172+
173+
var dialer net.Dialer
174+
_, err = dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, "22"))
175+
return err == nil
176+
}
177+
178+
func configuredHostname() (string, error) {
179+
u, err := config.URL.Read()
180+
if err != nil {
181+
return "", err
182+
}
183+
url, err := url.Parse(u)
184+
if err != nil {
185+
return "", err
186+
}
187+
return url.Hostname(), nil
188+
}
189+
161190
func writeStr(filename, data string) error {
162191
return ioutil.WriteFile(filename, []byte(data), 0777)
163192
}

0 commit comments

Comments
 (0)