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

时间:2017-05-17 16:45:53

标签: google-cloud-platform google-cloud-ml google-cloud-ml-engine

我有一个服务帐户,我已授予Viewer角色,并已下载凭据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。我不确定我做错了什么 - 我为凭证设置了正确的环境变量,根据他们的文档,服务帐户只需要Viewer角色来访问此端点。我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

我建议明确而不是依赖于Using CloudML prediction API in production without gcloud中的默认行为。此外,如果您致电:

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

您是否看到具有角色/查看者或更高级别的预期服务帐户?如果不是,您需要授予它权限。它在服务帐户页面中的存在仅表示您拥有该服务帐户,而不是允许它执行任何操作!

答案 1 :(得分:0)

Solved the same problem with the next steps:

  1. Create service account (role Project Viewer)
  2. Download json file with credentials
  3. Call it using

    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)