使用 Python 3.11 时,GCP Secret Manager 访问“无效授权”错误 503

使用 Python 3.11 时,GCP Secret Manager 访问“无效授权”错误 503

真的搞砸了。我写了一段简单的代码只是为了能够访问机密,但每次运行它时,它都会抛出以下错误:

google.api_core.exceptions.RetryError: Deadline of 60.0s exceeded while calling target function, last exception: 503 Getting metadata from plugin failed with error: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})

下面是我的代码:

from google.cloud import secretmanager

def secretFinder(projectid, secretid, version):

    client = secretmanager.SecretManagerServiceClient()
    name = f"projects/{projectid}/secrets/{secretid}/versions/{version}"
    response = client.access_secret_version(name=name)
    return response.payload.data.decode('UTF-8')

secretFinder("my_project", "test", "latest")

我的 CLI 已通过我的服务帐户进行身份验证,该帐户包含与其关联的以下角色 -

Owner
Secret Manager Admin
Secret Manager Secret Accessor

我确认只有我的帐户通过运行获得授权 

gcloud auth list

接下来,我通过运行来确保设置了正确的项目

gcloud config set project PROJECT_ID

其中项目 ID 为“my_project”。我没有使用项目编号,而是按照指示使用了实际项目 ID。 

讽刺的是,如果我通过 cli 运行以下命令,我实际上会得到我的秘密:

gcloud secrets versions access --secret=test latest

我真的不知道现在该怎么办,如果能提供任何帮助我将非常感激。

提前致谢!

答案1

运行gcloud auth application-default login并重试。

如果这不起作用,请将此问题移至 Stack Overflow。添加有关运行代码的环境的详细信息。

注意:CLIgcloud使用的凭据与您的代码不同。您的代码使用的是 ADC(应用程序默认凭据),这就是为什么您必须使用application-default命令选项进行身份验证。

您的另一个选择是修改代码并将服务帐户指定为参数SecretManagerServiceClient()

相关内容