Last active
August 7, 2023 14:07
-
-
Save matthewlenz/61f731319d48f41d1f036075aa92c522 to your computer and use it in GitHub Desktop.
Temporarily add SSH access for your current IP to your Google Cloud Compute instances.
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 | |
## If you've locked down all your ports for a project but need to access your instances via ssh (google cloud shell maybe?) | |
## this script might be of use to you. | |
EXPIRE=$(date +%s --date='now + 8 hours') | |
case "$1" in | |
add) | |
test -e ~/.tmp-ssh && echo "Rule exists, remove it first" && exit 1 | |
echo "Adding firewall rule allow-ssh-tmp-${EXPIRE}" | |
gcloud compute firewall-rules create "allow-ssh-tmp-${EXPIRE}" --allow tcp:22 --source-ranges "$(curl -s ipinfo.io/ip)" --quiet && echo $EXPIRE > ~/.tmp-ssh | |
;; | |
remove) | |
echo "Removing firewall rule allow-ssh-tmp-$(<~/.tmp-ssh)" | |
gcloud compute firewall-rules list --format='table[no-heading](name)' --filter="name = allow-ssh-tmp-$(<~/.tmp-ssh)" | xargs -r -I{} gcloud compute firewall-rules delete {} --quiet | |
rm ~/.tmp-ssh | |
;; | |
removeall) | |
gcloud compute firewall-rules list --format='table[no-heading](name)' --filter="name ~ ^allow-ssh-tmp" | xargs -r -I{} gcloud compute firewall-rules delete {} --quiet | |
;; | |
list) | |
gcloud compute firewall-rules list --format='table[no-heading](name)' --filter="name ~ ^allow-ssh-tmp" | |
;; | |
expire) | |
gcloud compute firewall-rules list --format='table[no-heading](name)' --filter="name ~ ^allow-ssh-tmp AND name < allow-ssh-tmp-$(date +%s)" | xargs -r -I{} gcloud compute firewall-rules dele | |
te {} --quiet | |
;; | |
*) | |
echo "tmp_ssh.sh add|remove|removeall|list|expire"; | |
exit 1; | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note. This isn't really needed anymore because you can lock down your ssh to google's IAP with a firewall rule that includes
35.235.240.0/20
. The web ssh provided by the google cloud console uses the IAP by default. When you connect from a google cloud shell or remote system that isn't accounted for in your firewall rules you can just use the additional--tunnel-through-iap
parameter to thegcloud compute ssh