Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Add config-ssh command #17

Merged
merged 6 commits into from
May 26, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Check if ssh is available
  • Loading branch information
cmoog committed May 26, 2020
commit ce4bb7d7298f99619401e889a293b719bd758762
45 changes: 37 additions & 8 deletions cmd/coder/config_ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import (
"context"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"time"

"cdr.dev/coder-cli/internal/config"
"cdr.dev/coder-cli/internal/entclient"
Expand All @@ -32,7 +34,7 @@ func (cmd *configSSHCmd) Spec() cli.CommandSpec {
return cli.CommandSpec{
Name: "config-ssh",
Usage: "",
Desc: "adds your Coder Enterprise environments to ~/.ssh/config",
Desc: "add your Coder Enterprise environments to ~/.ssh/config",
}
}

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

entClient := requireAuth()

sshAvailable := cmd.ensureSSHAvailable(ctx)
if !sshAvailable {
flog.Fatal("SSH is disabled or not available for your Coder Enterprise deployment.")
}

me, err := entClient.Me()
if err != nil {
flog.Fatal("failed to fetch username: %v", err)
Expand Down Expand Up @@ -129,18 +136,14 @@ func writeSSHKey(ctx context.Context, client *entclient.Client) error {
}

func (cmd *configSSHCmd) makeNewConfigs(userName string, envs []entclient.Environment) (string, error) {
u, err := config.URL.Read()
hostname, err := configuredHostname()
if err != nil {
return "", err
}
url, err := url.Parse(u)
if err != nil {
return "", err
return "", nil
}

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

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

func (cmd *configSSHCmd) ensureSSHAvailable(ctx context.Context) bool {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()

host, err := configuredHostname()
if err != nil {
return false
}

var dialer net.Dialer
_, err = dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, "22"))
return err == nil
}

func configuredHostname() (string, error) {
u, err := config.URL.Read()
if err != nil {
return "", err
}
url, err := url.Parse(u)
if err != nil {
return "", err
}
return url.Hostname(), nil
}

func writeStr(filename, data string) error {
return ioutil.WriteFile(filename, []byte(data), 0777)
}
Expand Down