This one took me a while to figure out, but if you want to get an Google access token from a Service Account key (JSON file), do this:
import json
import google.oauth2
import google.auth.transport.requests
import requests
KEY_FILE = "../private/my-project-key.json"
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
# Parse the key file to get its project ID
try:
with open(KEY_FILE, 'r') as f:
_ = json.load(f)
project_id = _.get('project_id')
except Exception as e:
quit(e)
try:
credentials = google.oauth2.service_account.Credentials.from_service_account_file(KEY_FILE, scopes=SCOPES)
_ = google.auth.transport.requests.Request()
credentials.refresh(_)
access_token = credentials.token
except Exception as e:
quit(e)
This token can then be used for Rest API calls by inserting in to the Authorization header like this:
instances = []
try:
url = f"https://compute.googleapis.com/compute/v1/projects/{project_id}/aggregated/instances"
headers = {'Authorization': f"Bearer {access_token}"}
response = requests.get(url, headers=headers)
_ = response.json().get('items')
for k, v in _.items():
instances.extend(v.get('instances', []))
except Exception as e:
quit(e)
print([instance.get('name') for instance in instances])