Note #2025-07-21-001

Srijan Choudhary Srijan Choudhary

gcloud_ssh

A simple script that finds a google cloud compute VM by IP address across all projects of an organization and runs gcloud ssh to it.

#!/bin/bash

GCLOUD_SSH_FLAGS="--internal-ip"

# Get organization ID dynamically
get_org_id() {
    gcloud organizations list --format="value(name)" --limit=1 2>/dev/null | sed 's|organizations/||'
}

search_and_connect() {
    local ip_address=$1

    echo "Searching for IP: $ip_address across organization..."

    # Get organization ID
    ORG_ID=$(get_org_id)
    if [ -z "$ORG_ID" ]; then
        echo "Failed to get organization ID. Make sure you have organization-level access."
        exit 1
    fi

    # Search for instance with this IP address
    RESULT=$(gcloud asset search-all-resources \
        --scope=organizations/$ORG_ID \
        --query="$ip_address" \
        --asset-types='compute.googleapis.com/Instance' \
        --format=json 2>/dev/null)

    if [ -z "$RESULT" ] || [ "$RESULT" = "[]" ]; then
        echo "IP address $ip_address not found in organization."
        exit 1
    fi

    # Parse JSON to extract instance details
    INSTANCE_NAME=$(echo "$RESULT" | jq -r '.[0].name' | sed 's|.*/||')
    PROJECT=$(echo "$RESULT" | jq -r '.[0].parentFullResourceName' | sed 's|.*/||')
    ZONE=$(echo "$RESULT" | jq -r '.[0].location' | sed 's|.*/||')
    STATE=$(echo "$RESULT" | jq -r '.[0].state')

    if [ "$INSTANCE_NAME" = "null" ] || [ "$PROJECT" = "null" ] || [ "$ZONE" = "null" ]; then
        echo "Failed to parse instance details from search result."
        echo "Raw result: $RESULT"
        exit 1
    fi

    # Check if instance is running
    if [ "$STATE" != "RUNNING" ]; then
        echo "Instance $INSTANCE_NAME is not running (state: $STATE)."
        echo "Cannot connect to a non-running instance."
        exit 1
    fi

    echo "Found instance: $INSTANCE_NAME in zone: $ZONE (project: $PROJECT)"

    # Generate and display the SSH command
    SSH_COMMAND="gcloud compute ssh $INSTANCE_NAME --zone=$ZONE --project=$PROJECT ${GCLOUD_SSH_FLAGS}"
    echo "SSH command: $SSH_COMMAND"

    # Execute the SSH command
    echo "Connecting to $INSTANCE_NAME..."
    exec $SSH_COMMAND
}

# Main script logic
case "${1:-}" in
    "")
        echo "Usage: $0 <IP_ADDRESS>"
        echo "  <IP_ADDRESS>  - Connect to instance with this IP"
        exit 1
        ;;
    *)
        search_and_connect "$1"
        ;;
esac

Interactions

πŸ” 1 repost