Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCP: How to get compute engine access token?

I want to get access token of compute engine. By using this access token, I want to call REST api. Further Rest api will be invoked using python 2.0 HTTP library. (not all google libraries are available, hence REST api are considered)

Could you please provide way to get compute engines access token? Following code can be staring point, however how to get access token from here onwards is not known:

from google.auth import compute_engine
credentials = compute_engine.Credentials() 

Please suggest different ways... Thanks in advance.

like image 909
Omkara Avatar asked Feb 28 '19 14:02

Omkara


People also ask

How do I access Google Compute Engine?

Browse to the Google Cloud Platform console and sign in if required using your Google account. Find and select your project in the project list. Select the “Compute -> Compute Engine” menu item. Locate your server instance and select the SSH button.

How do I find my GCP private key?

In Commander, from the Inventory tree, select the GCP cloud account, then select Actions > Edit Cloud Account. In the Edit Cloud Account dialog, for Private Key (JSON) File, browse to the location of the new private key.


1 Answers

Every Compute Engine instance stores its metadata on a metadata server. You can query this metadata server programmatically from within the instance for information about the instance such as service account information. You can request an access token from the metadata server in Python like so:

import requests

METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/'
METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
SERVICE_ACCOUNT = 'default'


def get_access_token():
    url = '{}instance/service-accounts/{}/token'.format(
        METADATA_URL, SERVICE_ACCOUNT)

    # Request an access token from the metadata server.
    r = requests.get(url, headers=METADATA_HEADERS)
    r.raise_for_status()

    # Extract the access token from the response.
    access_token = r.json()['access_token']

    return access_token

Note that this example assumes that your instance is using the Compute Engine default service account.

like image 61
LundinCast Avatar answered Sep 24 '22 23:09

LundinCast