Last active
April 21, 2021 00:45
-
-
Save ronoaldo/93396552e503ecab2154817077a6c8b2 to your computer and use it in GitHub Desktop.
Launch compute engine instance when connecting via SSH
This file contains hidden or 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
#!/bin/bash | |
set -x | |
# Get command options | |
export project="$1" | |
export zone="$2" | |
export vm="$3" | |
echo "Launching instance $project/$zone/$vm ..." | |
# Alias with project/zone options | |
gcloud="gcloud --project=$project" | |
# Check current status first | |
export status="$($gcloud compute instances describe --zone=$zone --format="value(status)" $vm)" | |
echo "$project/$zone/$vm: $status" | |
# Launch if not running yet | |
if [ "$status" != "RUNNING" ]; then | |
$gcloud compute instances start --zone=$zone $vm || true | |
fi | |
# Wait to boot | |
count=0 | |
while ! $gcloud compute instances get-serial-port-output --zone=$zone $vm | grep 'Startup finished in' ; do | |
sleep 1 | |
count=$(( count + 1 )) | |
if [ $count -gt 30 ] ; then | |
echo "Timed out after $count attempts" | |
exit 1 | |
fi | |
done | |
echo "Instance launched." |
This file contains hidden or 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
# Match and execute the launch script, so when connecting it will launch VM if it's not running | |
Match host myvm exec "/path/to/launch-gc-vm.sh myproject us-central1-f myvm" | |
# Use the IP address or DNS name if you have a public entry for the target host | |
# Also, you can use the SSH key that `gcloud compute ssh myvm` will generate for | |
Host myvm | |
HostName X.X.X.X | |
User myuser | |
IdentityFile /home/myuser/.ssh/google_compute_engine |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create a ~/.ssh/config entry using the Match directive, and point it to the script. When issuing
The script will launch the VM and wait for it to be running with the system booted before executing SSH. Pro-tip: add this to your Visual Studio Code Remote SSH and get an on-demand setup with an automated shutdown at late night!
PS: the "Wait to boot" part of the script is tested with Debian systemd log to serial output; adjust it to match your needs (or comment out if your boot sequence is fast; usually 30s is enought to boot on GCP, so a basic sleep 30 will be fine).