Skip to content

Commit

Permalink
d2vm/run: hetzner: use tcp to wait for the server to be ready, do not…
Browse files Browse the repository at this point in the history
… store server key in UserKnownHostsFile

Signed-off-by: Adphi <[email protected]>
  • Loading branch information
Adphi committed Sep 10, 2022
1 parent 9f702e5 commit dd1b500
Showing 1 changed file with 21 additions and 23 deletions.
44 changes: 21 additions & 23 deletions cmd/d2vm/run/hetzner.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"context"
"fmt"
"io"
"net"
"os"
"os/exec"
"strings"
"time"

"github.com/dustin/go-humanize"
Expand Down Expand Up @@ -242,38 +242,36 @@ func runHetzner(ctx context.Context, imgPath string, stdin io.Reader, stderr io.
if err := <-errs; err != nil {
return err
}
logrus.Infof("server created")
remove = false
args := []string{"-o", "StrictHostKeyChecking=no"}
if hetznerSSHKeyPath != "" {
args = append(args, "-i", hetznerSSHKeyPath)
}
args = append(args, fmt.Sprintf("%s@%s", hetznerSSHUser, sres.Server.PublicNet.IPv4.IP.String()))
makeCmd := func() *exec.Cmd {
cmd := exec.CommandContext(ctx, "ssh", args...)
cmd.Stdin = stdin
cmd.Stderr = stderr
cmd.Stdout = stdout
return cmd
}
logrus.Infof("waiting for server to be ready")
t := time.NewTimer(time.Minute)
wait:
for {
select {
case <-t.C:
return fmt.Errorf("ssh connection timeout")
case <-ctx.Done():
return ctx.Err()
default:
cmd := makeCmd()
if err := cmd.Run(); err != nil {
if strings.Contains(err.Error(), "exit status 255") {
time.Sleep(time.Second)
continue
}
return err
} else {
return nil
conn, err := net.Dial("tcp", fmt.Sprintf("%s:22", sres.Server.PublicNet.IPv4.IP.String()))
if err == nil {
conn.Close()
break wait
}
time.Sleep(time.Second)
}
}
args := []string{"-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null"}
if hetznerSSHKeyPath != "" {
args = append(args, "-i", hetznerSSHKeyPath)
}
args = append(args, fmt.Sprintf("%s@%s", hetznerSSHUser, sres.Server.PublicNet.IPv4.IP.String()))
cmd := exec.CommandContext(ctx, "ssh", args...)
cmd.Stdin = stdin
cmd.Stderr = stderr
cmd.Stdout = stdout
if err := cmd.Run(); err != nil {
return err
}
return nil
}

0 comments on commit dd1b500

Please sign in to comment.