Saturday, August 26, 2023

Shell script to find Public IP address in GCP

 Lets say you have a public ip that you bought and assigned to one of the instance in GCP project, you can use the below shell script to find:

In below code I am filtering the name of project that starts with cust. First login with below command:


gcloud auth login


#!/bin/bash


# Get a list of project IDs with names starting with "cust"

project_ids=$(gcloud projects list --format="value(projectId)" --filter="name:cust*")


# Loop over each project ID

for project_id in $project_ids; do

    echo "Checking project: $project_id"

    

    # Get a list of instance names in the current project

    instance_names=$(gcloud compute instances list --project "$project_id" --format="value(name)")


    # Loop over each instance in the current project

    for instance_name in $instance_names; do

        # Get the public IP address of the instance

        public_ip=$(gcloud compute instances describe "$instance_name" --project "$project_id" --format="value(networkInterfaces[0].accessConfigs[0].natIP)")

        

        echo "Instance: $instance_name, Public IP: $public_ip"

        echo "Instance: $instance_name, Public IP: $public_ip" >> /tmp/ip_details.txt

    done

done