Skip to content

Instantly share code, notes, and snippets.

@johananl
Created March 28, 2022 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johananl/4ff79c4b87c88020241bf84267d6368d to your computer and use it in GitHub Desktop.
Save johananl/4ff79c4b87c88020241bf84267d6368d to your computer and use it in GitHub Desktop.
A good retry loop in Go
const maxAttempts = 10
const retryIntervalSeconds = 5
var sshConnected bool
log.Printf("Connecting to VM using SSH")
for i := 0; i < maxAttempts; i++ {
if i > 0 {
time.Sleep(time.Second * retryIntervalSeconds)
log.Printf("Retrying SSH connection - attempt #%d of %d", i+1, maxAttempts)
}
client, err = ssh.Dial("tcp", fmt.Sprintf("%s:22", *ip.IPAddress), config)
if err != nil {
log.Printf("SSH error: %v", err)
continue
}
log.Printf("Connected!")
sshConnected = true
break
}
if !sshConnected {
log.Println("Could not connect to VM in time")
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment