Manisai Bashetty
Manisai Bashetty

Reputation: 37

How to get the list of gcp compute instances IP address through API externally

what is the procedure for getting the list of all the IP address of google compute instances through its API's and how to provide OAuth 2 access token externally

When I am trying to access via the API given by GCP

https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances

I am getting the following error

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Login Required.",
        "domain": "global",
        "reason": "required",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "UNAUTHENTICATED"
  }
}

How do i authenticate ?

Upvotes: 1

Views: 1393

Answers (1)

LundinCast
LundinCast

Reputation: 9810

The easiest way to get an access token for a curl call to a Google Cloud API is to use the Cloud SDK (provided you have it installed and configured).

Once you've confirmed you're logged in with the correct user or service account (gcloud auth list) you can get an access token for a user account by running:

gcloud auth print-access-token

or for a service account you've configured as default:

gcloud auth application-default print-access-token

You'll need to pass that token as Authorization header to authenticate your call. You can integrate the gcloud command in your curl call like this:

curl https://compute.googleapis.com/compute/v1/projects/PROJECT/zones/ZONE/instances -H "Authorization: Bearer $(gcloud auth print-access-token)"

You can use jq to parse the response and print only an array of IP objects, for example:

curl https://compute.googleapis.com/compute/v1/projects/PROJECT/zones/ZONE/instances -H "Authorization: Bearer $(gcloud auth print-access-token)" | jq '[.items | .[] | {ip: .networkInterfaces[].accessConfi
gs[].natIP}]'

It'll print a response of the form:

[
  {
    "ip": "XX.XXX.XX.XXX"
  },
  {
    "ip": "XXX.XXX.XX.XXX"
  }
]

Upvotes: 1

Related Questions