用户没有资源所需的权限 ml.versions.predict (Cloud ML Engine)

The user doesn't have the required permission ml.versions.predict on the resource (Cloud ML Engine)

我有一个已授予查看者角色的服务帐户,并下载了凭据 json 文件并为其设置了正确的环境变量。我正在尝试 运行 此处的示例:

def predict_json(project, model, instances, version=None):
    """Send json data to a deployed model for prediction.

    Args:
        project (str): project where the Cloud ML Engine Model is deployed.
        model (str): model name.
        instances ([Mapping[str: Any]]): Keys should be the names of Tensors
            your deployed model expects as inputs. Values should be datatypes
            convertible to Tensors, or (potentially nested) lists of datatypes
            convertible to tensors.
        version: str, version of the model to target.
    Returns:
        Mapping[str: any]: dictionary of prediction results defined by the
            model.
    """
    # Create the ML Engine service object.
    # To authenticate set the environment variable
    # GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
    service = googleapiclient.discovery.build('ml', 'v1beta1')
    name = 'projects/{}/models/{}'.format(project, model)

    if version is not None:
        name += '/versions/{}'.format(version)

    response = service.projects().predict(
        name=name,
        body={'instances': instances}
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']

但是,这给了我 403 和错误 The user doesn't have the required permission ml.versions.predict on the resource projects/project/models/model/versions/version。我不确定我做错了什么 - 我正在为凭据设置正确的环境变量,并且根据他们的文档,服务帐户只需要查看者角色即可访问此端点。我做错了什么?

tl;dr discovery.build 可能没有使用预期的服务帐户,因为它尝试了许多身份验证选项

我建议明确而不是依赖默认行为,如:。此外,如果您调用:

,您的项目 IAM 设置可能不包括服务帐户
gcloud --project "$PROJECT" get-iam-policy 

您是否看到 roles/viewer 或以上的预期服务帐户?如果不是,则需要授予它权限。它出现在服务帐户页面中仅表示您拥有该服务帐户,并不代表它可以做任何事情!

通过后续步骤解决了同样的问题:

  1. 创建服务帐户(角色 Project Viewer)
  2. 使用凭证下载 json 文件
  3. 使用

    调用

    from oauth2client.service_account import ServiceAccountCredentials

    from googleapiclient import discovery

    credentials = ServiceAccountCredentials.from_json_keyfile_name('your_creds.json')

    service = discovery.build('ml', 'v1', credentials=credentials)