Created
March 28, 2022 19:09
-
-
Save johananl/4ff79c4b87c88020241bf84267d6368d to your computer and use it in GitHub Desktop.
A good retry loop in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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