Home > Enterprise >  Can we use the default service account of a VM in gcp to call api's?
Can we use the default service account of a VM in gcp to call api's?

Time:06-27

I am trying to list the Storage Buckets within an Organization using REST API. I am running this code in a VM, currently I created a user managed Service Account and passing its key as a credential in the code.

Instead of passing the Service Account key as a credential:

  1. Can i use the service account of the VM to list the Storage Buckets in an Organization?
  2. How can we configure the code to use the VM service account?

CodePudding user response:

  1. Yes we can use the service account.
  2. Define VM service account as the authentication in code. You can try this code snippet based from the official documentation. Make sure that the correct dependencies are installed and you have the copy of the Service Account inside the local of the VM Instance.
def explicit():
    from google.cloud import storage

    # Explicitly use service account credentials by specifying the private key
    # file.
    storage_client = storage.Client.from_service_account_json(
        'service_account.json')

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

CodePudding user response:

I understand you run you code inside Google Cloud under some service account. And you would like to use some Google Cloud services APIs. In your example - storage API.

In that case you might not need any keys or json files. You might prefer to grant your service account relevant IAM roles explicitly, maybe during deployment time. And in you code it would not be necessary to create a storage client using some key file.

  • Related