Jeffrey Rennie
Jeffrey Rennie

Reputation: 3443

Given an IP address, how do I find which GCP Compute Engine instance it belongs too?

I got a security warning like:

Security vulnerability found in server running at 123.45.67.89.

I have lots of Google Cloud Platform projects, and lots of instances running in each project. How do I find which Compute Engine instance this ip address belongs to?

Upvotes: 6

Views: 10492

Answers (3)

Ryan Kistler
Ryan Kistler

Reputation: 61

so... if anyone else needs to do this and ends up here, like I did. You can literally use the search bar at the top of the google cloud interface to search for an IP.

Upvotes: 6

FridayPush
FridayPush

Reputation: 916

Use the gcloud commandline tool with a filter.

gcloud compute instances list --filter="EXTERNAL_IP=123.45.67.89"

edit: Missed the many projects requirements. Using bash:

project_names=( "project1" "project2" "project3" )
for i in ${project_names[@]}; do gcloud compute instances list --filter="EXTERNAL_IP=123.45.67.89" --project=$i; done;

Upvotes: 5

Jeffrey Rennie
Jeffrey Rennie

Reputation: 3443

This PowerShell script will do the job. It uses gcloud.

<#
.SYNOPSIS
    Given an IP address, finds a GCP Compute instance with the ip address.
.EXAMPLE
    PS C:\> .\Get-GcpInstance.ps1 --IpAddress 1.2.3.4
.OUTPUTS
    The GCP instance information.
#>
Param(
    [string][Parameter(Mandatory=$true)] $IpAddress
)

function Get-GcpInstance {
    param (
        [string][Parameter(Mandatory=$true)] $IpAddress,
        [string[]][Parameter(Mandatory=$true)] $ProjectIds
    )
    foreach ($projectId in $projectIds) {
        $instances = gcloud compute instances list -q --project=$projectId --format=json | ConvertFrom-Json
        foreach ($instance in $instances) {
            foreach ($networkInterface in $instance.networkInterfaces) {
                if ($networkInterface.networkIp -eq $IpAddress) {
                    return $instance                    
                }
                foreach ($accessConfig in $networkInterface.accessConfigs) {
                    if ($accessConfig.natIP -eq $IpAddress) {
                        return $instance
                    }
                }
            }
        }
    }
}

Get-GcpInstance $IpAddress (gcloud projects list --format=json | ConvertFrom-Json).ProjectId

I posted a slightly more sophisticated version of the script here: https://github.com/SurferJeffAtGoogle/scratch/blob/master/FindIp/Get-GcpInstance.ps1 It's more sophisticated because it only examines projects that I own, and it displays a progress bar.

P.S. Powershell runs on Linux and Mac too! I wrote this code on Linux.

Upvotes: 5

Related Questions