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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With