Skip to content
Advertisement

Why do I get `secretmanager.versions.access` denied in GCP?

I am trying to access a secret stored in secrets manager.

I created a service account with owner role. I created a key from it. I run:

import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './keyfile.json'
from google.cloud import secretmanager
secret_client = secretmanager.SecretManagerServiceClient()
secret_name = f'projects/{project_id}/secrets/{secret_id}/versions/{version_id}'
response = secret_client.access_secret_version(request={"name": secret_name})

but I get:

google.api_core.exceptions.PermissionDenied: 403 Permission 'secretmanager.versions.access' 
denied for resource 'projects/myprojnumber/secrets/mysecret/versions/1' (or it may not exist).

I checked the secret_name was the same as the secret’s value in secret manager.

I have tried adding Secret Manager Secret Accessor and Secret Manager Viewer roles.

Edit: running this from cloud shell.

Advertisement

Answer

I think the issue is that the code is taking the Default Credentials of the Cloud Shell instead of using your SA key.

You can specify the credentials when creating the client

from google.cloud import secretmanager
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file("./keyfile.json")

secret_client = secretmanager.SecretManagerServiceClient(credentials=credentials)
secret_name = f'projects/{project_id}/secrets/{secret_id}/versions/{version_id}'
response = secret_client.access_secret_version(request={"name": secret_name})

Another option using some of the methods found in the library docs:

from google.cloud import secretmanager

secret_client = secretmanager.SecretManagerServiceClient.from_service_account_file("./keyfile.json")
secret_name = f'projects/{project_id}/secrets/{secret_id}/versions/{version_id}'
response = secret_client.access_secret_version(request={"name": secret_name})

Just as an advice, being newbie does not mean you cannot Google a little more to search for something like how to use a SA as credential for the client of the library you’re using.

For example you could easily find this doc which shows a sample.

Anyway, good luck with GCP!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement