0

When ssh with PublicIpAddress fails, run ssh with PrivateIpAddress. I'm handling this way but it doesn't seem to work, ssh with PublicIpAddress exits with code 255 and doesn't try ssh with PrivateIpAddress.

    for _, machine := range selected {
        err := ssh(machine.KeyName, Username, machine.PublicIpAddress)
        if err != nil {
            err = ssh(machine.KeyName, Username, machine.PrivateIpAddress)
        }
        if err != nil {
            fmt.Println(err)
        }
    }

SSH func

func ssh(keyname string, user string, address string) error {
  var err error
  //

  if err := cmd.Run(); err != nil {
        fmt.Println(err.Error())
  }
  return err
}
badman
  • 319
  • 1
  • 12
  • Shouldn't your condition be `if err != nil` instead of `if err == nil` to call `ssh()` with private IP address? – icza Dec 08 '22 at 09:48
  • @icza mistake, edited. – badman Dec 08 '22 at 09:49
  • So what do you expect? Why do you write it doesn't seem to work? – icza Dec 08 '22 at 09:51
  • I expected that when the ssh connection with publicipaddress timeout or throws an error, it should try running the ssh connection with the privateipaddress. – badman Dec 08 '22 at 09:53
  • Now it justs exits with 255 and doesn't try the ssh with privateipaddress – badman Dec 08 '22 at 09:54
  • Inside `ssh()` you should return a non-`nil` error when the exit code is `255`. I assume you return `nil` but we don't see what's inside `ssh()`. – icza Dec 08 '22 at 09:57
  • I just update the ssh func to reflect that `if err := cmd.Run(); err != nil { fmt.Println(err.Error())} ` – badman Dec 08 '22 at 10:02
  • 1
    There's your error: you used short variable declaration which creates a new `err` variable shadowing the outer one. Use `=` instead of `:=`, like this `if err = cmd.Run(); err != nil {}` – icza Dec 08 '22 at 10:04

0 Answers0