简体   繁体   中英

Can I use the service account of a GCP VM (xxx-compute@developer.gserviceaccount.com) instead of SA json file to make api calls using python?

Currently, I am using some xxxx service account credential json file to make REST API Calls

from logging import exception
import requests
import ast
import json
import re
import sys
import subprocess
import os
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
from datetime import datetime
from datetime import timedelta

main_list = []

# Get the credentials from service account
credentials = service_account.Credentials.from_service_account_file("path to the json file")
service = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)

I do not want to use this json file anymore, instead i want to use Compute Engine service account (xxx-compute@developer.gserviceaccount.com) to call API's, Can someone tell me what change i have to do in python so that it uses VM's service account??

I encourage you to use Application Default Credentials (ADC) .

See this Python example .

ADCs means your code is unchanged whether you run it locally or on Google Cloud.

When you test your code off Google Cloud, you can export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json and ADC will use the exported credentials.

When you deploy your code to Google Cloud, ADC obtains the credentials (for the resource that's running the code) from Google's Metadata service.

For example, when you run ADC code on Compute Engine, ADC will obtain the instance's (.) Service Account.

You should try to always use instance|role-specific Service Accounts but the default Compute Engine account is a Service Account too and will work.

Be aware that you'll need to ensure that whatever Service Account(s) is/are used have the correct IAM permissions to access other services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM