Created
November 22, 2022 22:30
-
-
Save so-jelly/991bfe9333307d827d894eae872ca9d8 to your computer and use it in GitHub Desktop.
cloud vm
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 -eEo pipefail | |
set -x | |
print_usage() { | |
cat <<HELP_USAGE | |
Usage: | |
$0 [-p <project>] [-z <zone>] <vm_name> | |
-p Project the VM belongs to | |
-z Zone the VM is in | |
HELP_USAGE | |
} | |
while getopts 'p:z:h:' flag; do | |
case "${flag}" in | |
h) _host="${OPTARG}" ;; | |
p) _project="${OPTARG}" ;; | |
z) _zone="${OPTARG}" ;; | |
*) | |
print_usage | |
exit 1 | |
;; | |
esac | |
done | |
# remove all options | |
shift $((OPTIND - 1)) | |
_host="${_host:-$1}" | |
# use configured project and zone if not specified | |
_project=${_project:-$(gcloud config get project)} | |
_zone=${_zone:-$(gcloud config get compute/zone)} | |
# start VM if not already running | |
if | |
gcloud compute instances describe "${_host}" \ | |
--project "${_project}" --zone "${_zone}" \ | |
--format='value(status)' | | |
grep -vq 'RUNNING' | |
then | |
gcloud compute instances start "${_host}" --project "${_project}" --zone "${_zone}" | |
fi | |
until | |
# use '-n' so we don't mess with outer ssh session | |
gcloud compute ssh --project "${_project}" --zone "${_zone}" "${_host}" -- -n true | |
do :; done | |
# connect tunnel to stdin | |
gcloud compute start-iap-tunnel \ | |
"${_host}" 22 \ | |
--project "${_project}" --zone "${_zone}" \ | |
--listen-on-stdin \ | |
--verbosity=warning |
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
Host instance-1 | |
# User depending on oslogin $USER or $(gcloud config get account) | |
ProxyCommand gcloud_connect -p unique-project -z instance-zone -h %h | |
IdentityFile ~/.ssh/google_compute_engine |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment