Skip to content

Instantly share code, notes, and snippets.

@nickcmiller
Last active May 6, 2024 18:53
Show Gist options
  • Save nickcmiller/45d144700f6df15bdb249cbf097b5f04 to your computer and use it in GitHub Desktop.
Save nickcmiller/45d144700f6df15bdb249cbf097b5f04 to your computer and use it in GitHub Desktop.
Create .ssh config to remotely access GCE instance
#!/bin/bash
# Get instance name as an argument or use demo-instance as default
INSTANCE_NAME=${1:-demo-instance}
# Get zone as an argument or use us-west4-b as default
ZONE=${2:-us-west4-b}
# Location of Private Key created during authentication
PRIVATE_KEY_PATH=~/.ssh/google_compute_engine
# Check if the instance is running
INSTANCE_STATUS=$(gcloud compute instances describe $INSTANCE_NAME --zone=$ZONE --format='get(status)')
# If the instance is not running, tell the user to start the instance first and exit the script
if [ "$INSTANCE_STATUS" != "RUNNING" ]; then
echo "Instance $INSTANCE_NAME is not running. Please start the instance first."
exit 1
fi
# Get the public IP address of the instance
PUBLIC_IP=$(gcloud compute instances describe $INSTANCE_NAME --zone=$ZONE --format='get(networkInterfaces[0].accessConfigs[0].natIP)')
# Get the username of the instance
USERNAME=$(gcloud compute ssh $INSTANCE_NAME --zone $ZONE --dry-run | awk -F'[@ ]' '{print $(NF-1)}')
# Ensure .ssh key is added to project metadata by logging in to the instance and running a command
gcloud compute ssh $INSTANCE_NAME --zone $ZONE --command "echo 'Hello from $INSTANCE_NAME.'"
echo "Public IP: $PUBLIC_IP"
echo "Username: $USERNAME"
echo "Identity file: $PRIVATE_KEY_PATH"
# Append config to .ssh/config
cat << EOF >> ~/.ssh/config
Host $PUBLIC_IP
HostName $PUBLIC_IP
IdentityFile $PRIVATE_KEY_PATH
User $USERNAME
EOF
# ALTERNATIVE TO CONFIG CREATION: SSH into the instance
# ssh -i $PRIVATE_KEY_PATH $USERNAME@$PUBLIC_IP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment